Jupyter客户端通过Python连接到正在运行的内核

2024-04-26 23:11:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试以编程方式(使用Python)与运行中的jupyter内核进行交互,作为原型实验。在

我有一个jupyter笔记本在我的浏览器中运行,我通过magic命令从笔记本上获取连接信息

%connect_info
{
 "signature_scheme": "hmac-sha256",
 "shell_port": 49545,
 "kernel_name": "",
 "iopub_port": 49546,
 "stdin_port": 49547,
 "hb_port": 49549,
 "control_port": 49548,
 "key": "1a359267-f30d84302c39d352d6ac17c3",
 "transport": "tcp",
 "ip": "127.0.0.1"
}

KernelClient类的jupyter_client docs让我相信,我可以连接到这个信息,用这个对象监听/显示代码,并通过我连接到的内核发送要执行的代码,但是,我对我一直在尝试的东西没有任何运气,例如:

^{pr2}$

编辑:为了清楚起见,我添加了这个部分,给了@samh。建议我这样做,但没用

>>> from jupyter_client import KernelClient
>>> kc = KernelClient()
>>> kc.load_connection_info(connection)
>>> kc.start_channels()
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path/to/jupyter-nb/lib/python3.5/site-packages/jupyter_client/client.py", line 101, in start_channels
  self.shell_channel.start()
  File "/path/to/jupyter-nb/lib/python3.5/site-packages/jupyter_client/client.py", line 143, in shell_channel
  socket, self.session, self.ioloop
  TypeError: object() takes no parameters

Tags: inselfinfoclient信息portline笔记本
1条回答
网友
1楼 · 发布于 2024-04-26 23:11:20

我以前玩过KernelClient,虽然有一点点成功,但也有非常少的成功。我唯一的方法就是通过KernelManager(你没有)。例如尝试:

from jupyter_client import KernelManager
km = KernelManager()
km.start_kernel()
kc = km.client()
# now execute something in the client
kc.execute("2+2")
while True:
    try:
        kc_msg = kc.get_iopub_msg(timeout=1)
        if 'content' in kc_msg and 'data' in kc_msg['content']:
            print('the kernel produced data {}'.format(kc_msg['content']['data']))
            break        
    except:
        print('timeout kc.get_iopub_msg')
        pass

通常(但不总是)返回:

^{pr2}$

我做了一个快速的谷歌搜索,我找到的唯一一个左右的代码是:This post。在

我希望答案是正确的。如果你成功了,我很乐意学习。在

相关问题 更多 >