无法从 Notebook 中的 Javascript 调用 Python 函数

ppn*_*012 5 python ipython jupyter

我想say_hello在 Jupyter Notebook 中调用该函数。

def say_hello():
  print('hello')

%%javascript
//What have been tried
// Method 1
var kernel = IPython.notebook.kernel;
kernel.execute("say_hello()", {"output": callback});

// Method 2
Jupyter.notebook.kernel.execute("say_hello()")
Run Code Online (Sandbox Code Playgroud)

这两种方法都会ReferenceError在浏览器控制台中抛出。

VM5326:7 Uncaught ReferenceError: IPython is not defined
    at send_message (<anonymous>:7:22)
    at onClickSendMessage (<anonymous>:12:9)
    at HTMLButtonElement.onclick (app.ipynb:1)
Run Code Online (Sandbox Code Playgroud)

版本:JupterLab 3.5、IPython 7.16、Python 3.9.1

Jak*_*tný 7

在ReferenceError你得到由Jupyter和IPython都造成全局并不是在所有的在Jupyter实验室提供。您必须自己编写 JupyterLab 扩展。

不过,这些东西在 Jupyter Notebooks 中确实有效。您尝试的两种方法都是一个好的开始,但需要一些改进。

我们需要 3 个单元格 - Python、HTML 和 JS 之一。

  1. 让我们定义我们想要在 Python 中从 JS 调用的方法。
def say_hello():
    print('hello')
Run Code Online (Sandbox Code Playgroud)
  1. 我们需要创建一个单元格输出,JS 将在其中写入执行结果。
%%html
<div id="result_output">
Run Code Online (Sandbox Code Playgroud)
  1. 我们执行 Python 函数,并在回调中处理执行结果。从回调中,我们将结果文本填充到我们上面创建的输出中。
%%javascript
const callbacks = {
    iopub: {
        output: (data) => {
            // this will print a message in browser console
            console.log('hello in console')

            // this will insert the execution result into "result_output" div
            document.getElementById("result_output").innerHTML = data.content.text
        }
    }
};

const kernel = Jupyter.notebook.kernel
kernel.execute('say_hello()', callbacks)
Run Code Online (Sandbox Code Playgroud)

一些注意事项:

  • 如果您不需要查看结果,则第二个方法就足够了,执行已执行,仅不处理内核的结果(您可以在 Websocket 请求消息的浏览器开发工具的网络选项卡中看到)
  • 在您使用的方法 1 中,callback但您没有定义它 - 这会导致另一个ReferenceError
  • 使用比在 JS 中使用const 更好var
  • Jupyter.notebook.kernel 是相同的 IPython.notebook.kernel