安装 Brython 以在浏览器中获取 Python
JavaScript 不是您可以在浏览器中运行的唯一编程语言。 Brython 是一个用 JavaScript 实现的 Python 解释器,因此您可以在浏览器中运行 Python 代码。 这使您无需安装 Python 即可拥有 Python 交互式 shell。 您还可以编写 Python 代码来与 DOM 交互,并像使用 JavaScript 一样创建浏览器应用程序。 主要缺点是浏览器必须下载大约 6 兆字节的 JavaScript 文件才能运行,这可能会造成严重延迟。 这篇博文将指导您完成 Brython 的设置。
要“安装”Brython,请从 GitHub 上的 Brython 发布页面下载 zip 文件:https://github.com/brython-dev/brython/releases/。 (截至 2022 年 10 月,这是 Brython-3.11.0.zip)
此 zip 文件中包含 brython.js 和 brython_stdlib.js。 要在网页中获得交互式 shell,请使用文本编辑器创建一个 .html 文件并复制/粘贴以下代码:
<!doctype html> <html> <head> <script type="text/javascript" src="https://inventwithpython.com/blog/2022/10/31/installing-brython-to-get-python-in-your-browser/brython.js"></script> <script type="text/javascript" src="brython_stdlib.js"></script> <style> .codearea { background-color:#000; color:#fff; font-family:'Oxygen Mono', Consolas, 'Liberation Mono', 'DejaVu Sans Mono', monospace; font-size:14px; overflow:auto } </style> </head> <body onload=brython({"debug":1}) ><!-- remove the 1 to leave debug mode --> <noscript>Please enable Javascript to view this page correctly</noscript> <textarea id="code" class="codearea" rows="20" cols="100"></textarea> <script type="text/python3"> from interpreter import Interpreter # Start an interactive interpreter in textarea with id "code" Interpreter("code") </script> </body> </html>
在浏览器中打开此 .html 以查看交互式 shell:
您下载的 Brython zip 文件还有一个 demo.html 文件,其中展示了许多可以与文档对象模型 (DOM) 交互的 Python 代码示例。 而不是将 JS 代码放在 <script type="text/python">
标签,你把 Python 代码放在一个 <script type="text/python">
标签。
您还可以使用 pip 将 Brython 作为模块安装到您的 Python 安装中。 跑步 pip install brython
. 这将安装一个 brython-cli 脚本。 当你跑步时 brython-cli install
,该脚本会在当前目录中创建以下文件:
- README.txt brython.js brython_stdlib.js demo.html index.html unicode.txt
如果你跑 python -m http.server
在您的计算机上运行网络服务器,然后打开浏览器访问该地址 http://localhost:8000
您将看到在浏览器中呈现的 index.html 的内容。 右键单击网页并选择查看源代码(或在文本编辑器中打开 index.html)以查看 Brython 正在运行的 Python 代码:
<!doctype html> <html> <head> <meta charset="utf-8"> <script type="text/javascript" src="https://inventwithpython.com/blog/2022/10/31/installing-brython-to-get-python-in-your-browser/brython.js"></script> <script type="text/javascript" src="brython_stdlib.js"></script> </head> <body onload="brython(1)"> <script type="text/python"> from browser import document document <= "Hello" </script> </body> </html>
要创建在浏览器中运行的客户端 Web 应用程序,您必须学习 Brython 的用于与 DOM 交互的 API。 这在 Brython 文档中有详细解释。
您还可以查看 Susan Tan 的 PyCon 2014 演讲,浏览器中的 Python:Brython 简介