In an effort to isolate a minimum viable implementation, I was able to get responses back from the IPython kernel in just a couple of steps using essentially the same approach as ChrCury78.
Since I want to use the data returned from Python within Javascript, in these examples I just stored the message contents in a member on console
. (Unlike what ChrCury78 did, where he pushed the result to the output of the notebook cell.) In my real extension, I'll probably just attach it to a name on Jupyter
, or maybe an object of my own creation.
>> 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"
Multi-line Python code worked just fine, too; and, since I'd already imported Comm
, I didn't need to import it again:
>> 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 ]
If you want to keep the kernel namespace unpolluted afterward, you could add a del Comm
to the end of the Python command.
I'll definitely be writing wrapper functions of some kind for both of these operations.
This is with Python 3.9.11 and the following packages installed:
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