![]() |
创作新主题 |
docker Elasticsearch |
linux MongoDB Redis DATABASE NGINX 其他Web框架 web工具 zookeeper tornado NoSql Bootstrap js peewee Git bottle IE MQ Jquery |
机器学习算法 |
短视频 |
印度 |
在 index.html
文件的头部,我们导入了用于格式化的Tailwind CSS,Pyodide.js 0.20.0,以及CodeMirror及其依赖包。
UI有三个重要的组成部分:
1、Editor。用户可以在这里写Python代码。它是一个文本区域的HTML元素,其ID为代码。当我们初始化codemirror时,我们让它知道我们想用这个元素作为一个代码编辑器。
2、Output。显示代码输出的地方。它是一个id为output的textarea元素。当Pyodide执行Python代码时,它将把结果输出到这个元素。我们也在这个元素中显示一个错误信息。
3、Run button。当用户点击这个按钮时,我们抓取编辑器元素的值并将其作为一个字符串传递给
pyodide.runPython
。当 pyodide.runPython
返回结果时,我们在输出元素中显示它。
现在在项目的根部,创建 static/js
文件夹。然后,在 js
文件夹下,创建一个名为 main.js
的新文件。
static/js/main.js
:
// find the output element
const output = document.getElementById("output");
// initialize codemirror and pass configuration to support Python and the dracula theme
const editor = CodeMirror.fromTextArea(
document.getElementById("code"), {
mode: {
name: "python",
version: 3,
singleLineStringErrors: false,
},
theme: "dracula",
lineNumbers: true,
indentUnit: 4,
matchBrackets: true,
}
);
// set the initial value of the editor
editor.setValue("print('Hello world')");
output.value = "Initializing...\n";
// add pyodide returned value to the output
function addToOutput(stdout) {
output.value += ">>> " + "\n" + stdout + "\n";
}
// clean the output section
function clearHistory() {
output.value = "";
}
// init pyodide and show sys.version when it's loaded successfully
async function main() {
let pyodide = await loadPyodide({
indexURL: "https://cdn.jsdelivr.net/pyodide/v0.20.0/full/",
});
output.value = pyodide.runPython (`
import sys
sys.version
`);
output.value += "\n" + "Python Ready !" + "\n";
return pyodide;
}
// run the main function
let pyodideReadyPromise = main();
// pass the editor value to the pyodide.runPython function and show the result in the output section
async function evaluatePython() {
let pyodide = await pyodideReadyPromise;
try {
pyodide.runPython(`
import io
sys.stdout = io.StringIO()
`);
let result = pyodide.runPython(editor.getValue());
let stdout = pyodide.runPython("sys.stdout.getvalue()");
addToOutput(stdout);
} catch (err) {
addToOutput(err);
}
}
我们完成了以下步骤:
1、初始化CodeMirror,支持Python和Dracula主题。
2、初始化Pyodide。
3、添加了一个名为 evaluatePython
的函数,当用户点击运行按钮时执行。它将代码元素的值传递给 pyodide.runPython
,并通过 addToOutput
在输出元素中显示结果。
4、增加了一个叫 clearHistory
的函数,当用户点击 ClearHistory
按钮时,它将清除输出元素。
要在本地运行Flask开发服务器,请运行:
(env)$ flask run
现在服务器应该在5000端口运行。在你的浏览器中导航到 http://127.0.0.1:5000
,测试一下代码编辑器。
总结
在本教程中,主要讲解了如何使用WebAssembly在浏览器中运行Python代码,但一般来说,WebAssembly涵盖了更广泛的使用情况。
我们的部署平台比以往任何时候都更加多样化。WebAssembly可以影响客户端Web开发、服务器端开发、游戏、教育、云计算、移动平台、loT、serverless等方面。
本文完整源代码请扫描下方二维码加入会员后获取
- 点击下方阅读原文加入社区会员 -