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

使用PyScript嵌入Python程序到HTML网页后程序无法运行的问题求助

PyScript嵌入Python代码无法运行的解决方法

问题概述

HTML页面可正常加载,但通过<py-script src="pythonfile.py">引用的Python代码无法执行,代码中包含input()函数用于获取用户输入。

提供的代码

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <title>pyscript demo</title>
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>
    <py-script src="pythonfile.py"></py-script>
</body>
</html>

Python代码(pythonfile.py)

lst = [["a", 45], ["b", 40], ["c", 18], ["d", 17]]

name = input("Enter your name:")

print("Searching in list")
for item in lst:
    if item[0] == name:
        print("name:", item[0], "age:", item[1])

问题原因

  1. input()函数的兼容性问题:PyScript运行在浏览器环境中,原生Python的input()是终端交互逻辑,无法直接在网页中触发输入,会导致代码阻塞,后续逻辑无法执行。
  2. 文件路径或跨域问题:若pythonfile.py与HTML文件不在同一目录,或直接双击打开HTML文件(浏览器本地文件协议会有跨域限制),也会导致Python文件加载失败。

解决方案

方案1:使用浏览器弹窗获取输入

修改Python代码,调用浏览器的弹窗API获取输入,替代原生input():

import pyscript

lst = [["a", 45], ["b", 40], ["c", 18], ["d", 17]]

# 调用浏览器弹窗获取输入
name = pyscript.window.prompt("Enter your name:")

if name:  # 判断用户未点击取消按钮
    print("Searching in list")
    found = False
    for item in lst:
        if item[0] == name:
            print(f"name: {item[0]} age: {item[1]}")
            found = True
    if not found:
        print("Name not found in the list")

方案2:使用网页输入组件实现交互(推荐)

更符合网页交互逻辑,添加输入框和按钮,通过PyScript绑定事件触发查询:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>pyscript demo</title>
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>
    <!-- 网页输入组件 -->
    <input type="text" id="name-input" placeholder="Enter your name">
    <button py-click="search_name()">Search</button>
    <!-- 用于展示输出的容器 -->
    <div id="output"></div>

    <py-script>
        lst = [["a", 45], ["b", 40], ["c", 18], ["d", 17]]
        
        def search_name():
            # 获取输入框的值
            name = Element("name-input").value
            output = Element("output")
            output.clear()  # 清空之前的输出
            output.write("Searching in list")
            
            found = False
            for item in lst:
                if item[0] == name:
                    output.write(f"name: {item[0]} age: {item[1]}")
                    found = True
            if not found:
                output.write("Name not found in the list")
    </py-script>
</body>
</html>

额外注意事项

  • 确保pythonfile.py与HTML文件在同一目录下,若不在同一目录,需使用正确的相对路径(如src="./scripts/pythonfile.py")。
  • 避免直接双击打开HTML文件,建议使用本地服务器运行,比如执行python -m http.server命令,然后通过http://localhost:8000访问页面,规避浏览器跨域限制。

内容的提问来源于stack exchange,提问作者Mohamed Afzil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:15:33