基本使用方法
最简单的方式
新建一个名为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的基础库功能。
在上面两个文件加载完毕后,只要在网页中存在type为text/python的script,均会被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端即可。
同时运行同一网页中的多处代码
在 Web 环境中,Brython有一个名为__BRYTHON__的变量,封装了众多可直接运行JavaScript代码的方法,如:runPythonSource。顾名思义,就是运行Python代码。直接调用这些方法,我们的代码将更加灵活。
runPythonSource方法以同步的方式运行代码,因此无需考虑如何处理异步的状态。
下面调用它来运行多个Python源代码:
let pc;
function runSrc(src, pc) {
console.log = function(...msg) {
let str = msg[0];
str = str.replace('<', '<').replace('>', '>');
pc.log('%s', str);
};
__BRYTHON__.runPythonSource(src);
}
pc = getPC(); // get a pc instance holding the first output element
runSrc(`print('Hello')`, pc)
pc = getPC(); // get another pc instance holding the second output element
runSrc(`print(2 + 3)`, pc)
在运行源代码之前,先将console的输出重定向为由pc负责输出,然后再调用runPythonSource方法。这样,如果源代码中有输出语句,则改由pc来接管输出。实际效果如下。
第一处代码:
print('Hello')
第二处代码:
print(type('Hello'))