1

我正在尝试运行一个简单的 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

4

1 回答 1

3

基本上,您可以实现自己的打印功能。但是,如果你想完全使用print你可以从 JS 中重写该函数:

languagePluginLoader.then(()=>{
  pyodide.globals.print = s => s
})

它只返回输入参数,因为它的输出将被写入容器(.then(output => addToOutput(output)))。当然,您可以实现任何自定义行为,例如将输入直接写入容器。

这是完整的示例:

<!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)});
    }
    
    languagePluginLoader.then(()=>{
      // override default print behavior
      pyodide.globals.print = s => s
    })
  </script>
</body>

</html>

于 2021-04-13T00:37:07.513 回答