WebGL Tutorial
and more

Brython

撰写时间:2024-11-03

修订时间:2024-11-03

简介

Brython,让我们在Web端可以直接运行Python源代码。

一切都来得简直不要那么太简单!😄

可惜有一点美中不足,Brython官网经常无法访问。:(

基本使用方法

最简单的方式

新建一个名为hello-from-brython.html文件,内容如下:

<!DOCTYPE html> <html> <head> <title>Brython Demo</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.jsdelivr.net/npm/brython/brython.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/brython/brython_stdlib.js"></script> <script type="text/python"> from browser import document, html def consoleLog(): x = 20 y = 30 z = x + y print(f'z = {z}') def constructWebPage(): document <= html.H1('Welcome to Brython') document <= html.P('Brython brings to you with Python programming on Web.') document <= html.P('Open the console in your brower to have a look at some outputs in Python.') consoleLog() constructWebPage() </script> </head> <body> </body> </html>

运行网页

为原汁原味地体现Brython,上面的网页未加任何CSS样式。

加载了两个文件,brython.min.js提供Python的内置语言功能,brython_stdlib.js提供Python的基础库功能。

在上面两个文件加载完毕后,只要在网页中存在typetext/pythonscript,均会被Brython作为Python语言的源代码而编译为JavaScript代码,最终得以在Web端执行。

外置Python源代码

我们可以将Python源代码提取出来,存放为独立的.py文件。主文件:

<head> ... <script src="./brython.min.js"></script> <script src="./brython_stdlib.js"></script> <script src="hello.py" type="text/python"></script> </head>

Python源代码文件hello.py

from browser import document, html document <= html.H1("External Python File") document <= html.P("The contents in this page are from a stand-alone '.py' file.")

运行网页

这种方式,给了我们无限的自由:在对Python友好的IDE中编写并调试好Python源代码后,再将文件直接部署至Web端即可。

参考资源

  1. Python.org
  2. brython Home
  3. PyScript Home