python - 使用 KernelClient API 在 ipython 内核中执行代码

标签 python ipython jupyter

我有一个现有的 ipython 内核,带有一个通信文件“path/comm_file.json”,我想使用内核客户端 API 在这个内核中执行代码(实际上我并不挑剔,任何方法都可以..) .我知道这是从 jupyter 做事的最佳方式 documentation .所以我写了下面的代码:

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

但是execute方法会导致如下错误:

  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

我做错了什么??

最佳答案

我也在尝试弄清楚客户端是如何工作的。这是一个开始的地方:

对于一个简单的阻塞客户端,你可以看看如何jupyter_test_clientjupyter_console作品。

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)

您将需要辅助函数来正确处理 zmq channel 和 json 消息。

关于python - 使用 KernelClient API 在 ipython 内核中执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33731744/

相关文章:

python - dir 函数不显示所有包内容

python - 为什么这个正则表达式在 Rubular 中有效,但在 Python 中无效?

python - 使用 IPython 魔法计时 python 脚本

ipython - IPython Jupyter:上传文件夹

ipython - 无法在 Jupyter 中并行导入 IPython

linux - 在 JupyterHub 中创建的默认系统用户的密码

python - Pyinstaller & pandas : Python. 未找到运行时

python - 将 mmap 与 popen 一起使用

ipython - 以编程方式将单元添加到 ipython 笔记本以生成报告

python - 如何使调用者的命名空间可用于导入函数中的 IPython 魔法?