
借助 pyscript,你可以在纯 html 页面中嵌入并执行 python 代码,所有运算在用户浏览器中完成,无需后端服务器或 python 环境部署。
现代 Web 开发中,Python 通常运行在服务端(如 Flask/Django),但若你希望将轻量级 Python 逻辑(例如单词乱序、数据计算、表单校验等)直接集成到静态 HTML 页面中,并让每位访问者“开箱即用”地执行——PyScript 是目前最成熟、零配置的解决方案。
PyScript 是一个开源框架,它基于 WebAssembly 和 Pyodide,将 CPython 解释器编译为可在浏览器中安全运行的模块。这意味着:你的 main.py 会真正被解析执行,支持标准库(如 random, json, re)、第三方包(通过
✅ 快速上手示例:实现“单词随机打乱”功能
- 创建 index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Word Shuffler</title> <!-- 引入 PyScript(推荐使用 CDN 最新稳定版) --> <link rel="stylesheet" href="https://pyscript.net/releases/2024.11.1/pyscript.css" /> <script defer src="https://pyscript.net/releases/2024.11.1/pyscript.js"></script> </head> <body> <h2>Shuffle Your Words</h2> <input id="input-words" type="text" placeholder="Enter words, separated by spaces" value="apple banana cherry"> <button id="shuffle-btn">Shuffle!</button> <p><strong>Result:</strong> <span id="output"></span></p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p>
@when("click", selector="#shuffle-btn") def shuffle_words(): input_el = document.querySelector("#input-words") words = input_el.value.strip().split() if not words: display("Please enter at least one word.", target="output", append=False) return random.shuffle(words) result = " ".join(words) display(result, target="output", append=False)










