Executing code in ipython kernel with the KernelCl

2019-05-09 09:59发布

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??

2条回答
迷人小祖宗
2楼-- · 2019-05-09 10:20

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.

查看更多
我命由我不由天
3楼-- · 2019-05-09 10:37

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.

查看更多
登录 后发表回答