我最近遇到了pyodide项目 https://github.com/iodide-project/pyodide.
我已经使用 Pyodide 构建了一个小演示,但是尽管我花了很多时间查看源代码,但对我来说如何重定向还不清楚print
python 的输出(除了修改 CPython 源代码),以及如何将输出从 matplotlib.pyplot 重定向到浏览器。
从源代码来看,图画布Wasm https://github.com/iodide-project/pyodide/blob/master/packages/matplotlib/src/wasm_backend.py确实有一个show()
具有适当后端的方法来绘制到浏览器画布 - 但是,我不清楚如何实例化此类并调用它show()
方法或者确实,是否有另一种更明显的方法将绘图重定向到画布。
因此我的问题是:
- 我如何重定向
print()
消息
- 如何强制 pyodide 在浏览器中绘制 matplotlib 图形?
这是我的测试页面:
<!doctype html>
<meta charset="utf-8">
<html lang="en">
<html>
<head>
<title>Demo</title>
<script src="../../pyodide/build/pyodide.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
languagePluginLoader.then(() => {
pyodide.loadPackage(['matplotlib']).then(() => {
pyodide.runPython(`
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
#fig = plt.gcf()
#fig.savefig(imgdata, format='png')
print('Done from python!')`
);
//var image = pyodide.pyimport('imgdata');
//console.log(image);
});});
</script>
<html>
首先,让我们看看是否可以在浏览器中显示任何内容;例如一个普通的字符串。 Python 变量存储在pyodide.globals https://github.com/iodide-project/pyodide/blob/master/docs/api_reference.md#pyodideglobals属性。因此我们可以从那里取出 python 对象并将其放入<div>
页面上的元素。
<!doctype html>
<meta charset="utf-8">
<html>
<head>
<title>Demo</title>
<script src="../pyodide/pyodide.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
languagePluginLoader.then(() => {
pyodide.runPython(`my_string = "This is a python string." `);
document.getElementById("textfield").innerText = pyodide.globals.my_string;
});
</script>
<div id="textfield"></div>
<html>
现在我想我们可以用 matplotlib 图形做同样的事情。下面将显示文档中保存的 png 图像。
<!doctype html>
<meta charset="utf-8">
<html lang="en">
<html>
<head>
<title>Demo</title>
<script src="../pyodide/pyodide.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
languagePluginLoader.then(() => {
pyodide.loadPackage(['matplotlib']).then(() => {
pyodide.runPython(`
import matplotlib.pyplot as plt
import io, base64
fig, ax = plt.subplots()
ax.plot([1,3,2])
buf = io.BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
img_str = 'data:image/png;base64,' + base64.b64encode(buf.read()).decode('UTF-8')`
);
document.getElementById("pyplotfigure").src=pyodide.globals.img_str
});});
</script>
<div id="textfield">A matplotlib figure:</div>
<div id="pyplotdiv"><img id="pyplotfigure"/></div>
<html>
我还没有调查过backends.wasm_backend
然而,这可能允许以更自动化的方式执行上述操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)