【发布时间】:2021-07-07 01:31:18
【问题描述】:
我正在尝试运行一个简单的 pyodide 示例,但对 javascript 或 pyodide 不太熟悉,并且不确定为什么输出未定义。该语句执行得很好,因为我可以在控制台日志中看到正确的输出,但我无法将输出分配给文档。
这里是代码
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.languagePluginUrl = 'https://cdn.jsdelivr.net/pyodide/v0.17.0a2/full/';
</script>
<script src="https://cdn.jsdelivr.net/pyodide/v0.17.0a2/full/pyodide.js"></script>
</head>
<body>
<p>You can execute any Python code. Just enter something in the box below and click the button.</p>
<textarea id='code' style='width: 50%;' rows='10'>print('hello')</textarea>
<button onclick='evaluatePython()'>Run</button>
<br>
<br>
<div>
Output:
</div>
<textarea id='output' style='width: 50%;' rows='3' disabled></textarea>
<script>
const output = document.getElementById("output");
const code = document.getElementById("code");
// show output
function addToOutput(s) {
output.value = s;
}
function evaluatePython() {
let output = pyodide.runPythonAsync(code.value)
.then(output => addToOutput(output))
.catch((err) => { addToOutput(err)});
}
</script>
</body>
</html>
我从这里松散地遵循替代示例 -- https://pyodide.org/en/stable/using_pyodide_from_javascript.html
【问题讨论】:
-
此代码有效。问题是
print没有返回任何东西。尝试评估其他内容(例如1+1)。另外,看看这个tutorial -
请编辑您的问题并将您的代码包装在
html块中,以便其他人可以实时运行。 -
@ArayKarjauv 谢谢。不知道你可以现场运行它。此外,这完全有道理,当然 print() 不会返回任何内容。我试图做到这一点,以便用户可以键入任何 python 代码,包括打印,并且输出将显示在输出框中。目前,您可以在控制台中看到 print 语句的输出。我基本上想和ritabratamaiti.github.io/pyRunBrowser做同样的事情
-
@ArayKarjauv 另外,我确实看过你的教程。在我解决了上述问题后,我打算继续进行绘图。
-
这似乎是已知的事情github.com/pyodide/pyodide/issues/8
标签: javascript python html pyodide