为了隔离一个最小可行的实现,我能够使用与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