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

时间:2018-01-05 22:27:08

标签: python ipython jupyter-notebook jupyter

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

我的浏览器中运行了一个jupyter笔记本,我通过魔术命令从笔记本中获取了连接信息

for

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

%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"
}

编辑:为了清晰起见,在@Sam H.的基础上添加此部分。建议我这样做但是没有用

>>> from jupyter_client import KernelClient
>>> connection = {
  "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"
}
>>> client = KernelClient(**connection)
>>> client.history()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path/to/envs/jupyter-nb/lib/python3.5/site-packages/jupyter_client/client.py", line 347, in history
self.shell_channel.send(msg)
  File "/path/to/envs/jupyter-nb/lib/python3.5/site-packages/jupyter_client/client.py", line 143, in shell_channel
socket, self.session, self.ioloop
>>> client.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
 >>> client.load_connection_info(connection)
 >>> client.execute('print("Hello World")')
   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 254, in execute
self.shell_channel.send(msg)
   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

1 个答案:

答案 0 :(得分:2)

我过去曾与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

通常(但不总是)返回:

the kernel produced data {'text/plain': '4'}

我做了一个快速谷歌搜索,我发现的唯一代码或SO帖子有一些迹象表明我在正确的轨道上:This post

注意我认识到这绝不是一个完整的答案,但希望这是朝着正确方向迈出的一步。如果你取得了成功,我会很高兴学习。