Executing code in ipython kernel with the KernelClient API

一曲冷凌霜 提交于 2019-12-22 08:17:18

问题


I have an existing ipython kernel, with a communication file 'path/comm_file.json' and I want to execute code in this kernel using the Kernel Client API (actually I'm not picky, any method will do..). I understood that this is the best way to do things from the jupyter documentation. So I write the following code:

from jupyter_client import KernelClient
client = KernelClient(connection_file='path/comm_file.json')
client.execute('a = 10')

But the execute method leads to the following error:

  File "C:\Python27\lib\site-packages\jupyter_client\client.py", line 249, in execute
    self.shell_channel.send(msg)
  File "C:\Python27\lib\site-packages\jupyter_client\client.py", line 143, in shell_channel
    socket, self.session, self.ioloop
TypeError: object.__new__() takes no parameters

What am I doing wrong here??


回答1:


I am also trying to figure out how the client works. Here's a place to start:

For a simple blocking client you can have a look a how jupyter_test_client and jupyter_console works.

from pprint import pprint
from jupyter_client.consoleapp import JupyterConsoleApp

class MyKernelApp(JupyterConsoleApp):
    def __init__(self, connection_file, runtime_dir):
        self._dispatching = False
        self.existing = connection_file
        self.runtime_dir = runtime_dir
        self.initialize()

app = MyKernelApp("connection.json", "/tmp")
kc = app.kernel_client
kc.execute("print 'hello'")
msg = kc.iopub_channel.get_msg(block=True, timeout=1)
pprint(msg)

You will need helper functions to handle properly the zmq channels and json messages.




回答2:


I was able to make a simple and bare KernelClient work for me with this:

from jupyter_client.blocking import BlockingKernelClient

kc = BlockingKernelClient(connection_file='path/comm_file.json')

kc.load_connection_file()
kc.start_channels()

msgid = kc.execute('a = 10')
reply = kc.get_shell_msg(timeout=5)

That's indeed how JupyterConsoleApp (used by jupyter_console) initializes its client when an existing kernel file is given.



来源:https://stackoverflow.com/questions/33731744/executing-code-in-ipython-kernel-with-the-kernelclient-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!