
本文介绍使用最新版 pyscript(2024.4.1)实现“点击 html 按钮后运行独立 python 文件(如 main.py)”的完整方案,涵盖配置、事件绑定、安全执行及关键注意事项。
本文介绍使用最新版 pyscript(2024.4.1)实现“点击 html 按钮后运行独立 python 文件(如 main.py)”的完整方案,涵盖配置、事件绑定、安全执行及关键注意事项。
PyScript 并不支持在 JavaScript 中动态插入
以下是一个可直接运行的完整示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Secure Login</title>
<link rel="stylesheet" href="style.css">
<!-- ✅ 使用最新稳定版 PyScript CDN -->
<link rel="stylesheet" href="https://pyscript.net/releases/2024.4.1/core.css">
<script type="module" src="https://pyscript.net/releases/2024.4.1/core.js"></script>
</head>
<body>
<div class="main">
<h1>Secure Login</h1>
<h3>Enter your login credentials</h3>
<p>Not registered?
<a href="#" style="text-decoration: none;">Create an account</a>
</p>
<!-- ✅ 按钮需有唯一 ID 供事件绑定 -->
<button id="run-main">Run main.py</button>
</div>
<!-- ✅ 声明 main.py 为预加载文件 -->
<py-config>
[files]
"main.py" = "main.py"
</py-config>
<!-- ✅ Python 逻辑:监听按钮点击,读取并执行 main.py -->
<script type="py">
from pyscript import when
@when('click', '#run-main')
def run_main(evt):
try:
with open("main.py") as f:
exec(f.read(), globals())
print("✅ main.py executed successfully.")
except FileNotFoundError:
print("❌ Error: main.py not found. Please check file path and py-config.")
except Exception as e:
print(f"❌ Execution error: {e}")
</script>
</body>
</html>? 关键要点说明:
-
必须存在 :[files] 部分声明 main.py 为受信任的本地资源,PyScript 才允许 open() 访问;路径为相对当前 HTML 的位置(如与 HTML 同目录)。 - exec() 是唯一可行方式:PyScript 不提供 import 或 run_file() 等 API;exec() 在当前作用域执行代码,变量/函数将保留在全局命名空间中(注意命名冲突)。
- 安全性提示:仅对可信的本地 .py 文件使用此方法;避免从用户输入构造文件名,防止任意代码执行风险。
- 错误处理必不可少:main.py 不存在、语法错误或运行时异常均会导致静默失败,务必用 try/except 捕获并输出日志。
- 旧版兼容性警告:alpha 版本已废弃(2022 年发布),其 CSS/JS URL(如 htpps://pyscript.net/alpha/...)不仅失效,还含拼写错误(htpps → https),务必升级至 releases/2024.4.1 或更高版本。
? 进阶建议:若 main.py 功能复杂,推荐重构为模块化函数(如 def login_handler(): ...),并在
立即学习“Python免费学习笔记(深入)”;


















