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
在ReferenceError你得到由Jupyter和IPython都造成全局并不是在所有的在Jupyter实验室提供。您必须自己编写 JupyterLab 扩展。
不过,这些东西在 Jupyter Notebooks 中确实有效。您尝试的两种方法都是一个好的开始,但需要一些改进。
我们需要 3 个单元格 - Python、HTML 和 JS 之一。
def say_hello():
print('hello')
Run Code Online (Sandbox Code Playgroud)
%%html
<div id="result_output">
Run Code Online (Sandbox Code Playgroud)
%%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)
一些注意事项:
callback但您没有定义它 - 这会导致另一个ReferenceErrorconst 更好varJupyter.notebook.kernel 是相同的 IPython.notebook.kernel