gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:58:30 26 4
gpt4 key购买 nike

我有一个现有的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com