You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PyScript实现点击HTML按钮运行指定Python文件?

可行,以下是正确实现方法

你的需求可以通过PyScript实现,但当前代码存在几个关键错误导致无法运行:

  • PyScript的CDN链接拼写错误(htpps应为https)
  • 使用了中文引号(如rel=”stylesheet”),浏览器无法识别
  • 在JavaScript函数内直接写入<py-script>标签的方式无效,JS不能直接解析HTML标签
  • 按钮和script标签放在了</html>闭合标签之外,HTML结构非法

正确实现方案

方案1:直接用PyScript的py-click绑定按钮事件

这种方式最简洁,直接在按钮上通过py-click调用Python函数,同时加载外部main.py文件:

<!DOCTYPE html> 
<html> 
<head> 
    <title>Secure Login</title> 
    <link rel="stylesheet" href="style.css"> 
    <!-- 修正CDN链接和引号 -->
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    <!-- 加载外部Python文件 -->
    <py-script src="./main.py"></py-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> 
    </div>
    <!-- 绑定Python函数到按钮点击事件 -->
    <button py-click="run_main()">运行main.py</button>
</body> 
</html>

对应的main.py需要定义run_main()函数:

def run_main():
    # 这里写你要执行的代码逻辑
    print("main.py代码已运行")
    # 可以操作DOM,比如在页面显示结果
    from pyscript import Element
    Element("main").write("<p>main.py执行完成!</p>")

方案2:通过JavaScript触发Python代码执行

如果需要用JS控制执行时机,可以通过PyScript底层的pyodide对象调用Python代码:

<!DOCTYPE html> 
<html> 
<head> 
    <title>Secure Login</title> 
    <link rel="stylesheet" href="style.css"> 
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.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> 
    </div>
    <button onclick="runPython()">运行main.py</button>

    <script>
        async function runPython() {
            // 等待PyScript初始化完成
            await pyodide.loadPackage([]);
            // 加载并执行外部Python文件
            await pyodide.runPythonAsync(await (await fetch('./main.py')).text());
            // 若main.py定义了函数,可直接调用:
            // await pyodide.runPythonAsync("from main import run_main; run_main()");
        }
    </script>
</body> 
</html>

注意事项

  • 确保main.py和HTML文件在同一目录下,或者路径配置正确
  • PyScript运行在浏览器的WebAssembly沙箱中,无法访问本地文件系统的非公开资源
  • 如果main.py依赖第三方库,需要在<py-config>中声明,示例:
    <py-config>
        packages = ["requests"]
    </py-config>
    

内容的提问来源于stack exchange,提问作者Joshua Carlson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 11:45:22