为隔离出一个最小可行的实现,我采用了与
ChrCury78基本相同的方法,在仅几个步骤内就能从IPython内核获取响应。
由于我想在Javascript中使用从Python返回的数据,在这些示例中,我只是将消息内容存储在
console
的成员中。(不像ChrCury78那样,他把结果推到笔记本单元格的输出中)。在我的真正扩展中,我可能会将它附加到
Jupyter
上的名称或我自己创建的对象上。
>> Jupyter.notebook.kernel.comm_manager.register_target("mycomm", (comm, msg) => {comm.on_msg( m => {console.retval = m.content.data})})
<- undefined
>> Jupyter.notebook.kernel.execute("from ipykernel.comm import Comm; Comm(target_name='mycomm').send('FOO')")
<- "{hex UID}"
>> console.retval
<- "FOO"
多行Python代码也很好运行,而且既然我已经导入了
Comm
,就不需要再次导入它了。
>> Jupyter.notebook.kernel.execute("l = []\nfor x in range(5):\n l.append(x)\nComm(target_name='mycomm').send(l)")
<- "{hex UID}"
>> console.retval
<- Array(5) [ 0, 1, 2, 3, 4 ]
如果您想在之后保持内核命名空间的清洁,可以在 Python 命令的末尾添加 del Comm
。
我一定会为这两个操作编写某种包装函数。
这是使用 Python 3.9.11 和以下已安装的软件包:
ipykernel 6.9.2
ipython 8.1.1
ipython-genutils 0.2.0
ipywidgets 7.7.0
jupyter 1.0.0
jupyter-client 7.1.2
jupyter-console 6.4.3
jupyter-contrib-core 0.3.3
jupyter-contrib-nbextensions 0.5.1
jupyter-core 4.9.2
jupyter-highlight-selected-word 0.2.0
jupyter-latex-envs 1.4.6
jupyter-nbextensions-configurator 0.4.1
jupyterlab-pygments 0.1.2
jupyterlab-widgets 1.1.0