我想在一台机器上运行一个 IPython 实例并从另一个进程(通过 LAN)连接到它(运行一些 python 命令)。我知道使用 zmq 是可能的:http://ipython.org/ipython-doc/dev/development/ipythonzmq.html .
但是,我找不到有关如何执行此操作以及是否可行的文档。
任何帮助将不胜感激!
编辑
我希望能够连接到 IPython 内核实例并向其发送 python 命令。但是,这不应该通过图形工具 (qtconsole) 来完成,但我希望能够从不同的 python 脚本中连接到该内核实例...
例如
external.py
somehow_connect_to_ipython_kernel_instance
instance.run_command("a=6")
最佳答案
如果您想从另一个 Python 程序在内核中运行代码,最简单的方法是连接 BlockingKernelManager .现在最好的例子是 Paul Ivanov 的 vim-ipython客户端,或者 IPython 自己的 terminal client .
要点:
- ipython 内核写入 JSON 连接文件,位于
IPYTHONDIR/profile_<name>/security/kernel-<id>.json
,其中包含各种客户端连接和执行代码所需的信息。 - KernelManager 是用于与内核通信(执行代码、接收结果等)的对象。 *
一个工作示例:
在 shell 中,执行 ipython kernel
(或 ipython qtconsole
,如果您想与已运行的 GUI 共享内核):
$> ipython kernel
[IPKernelApp] To connect another client to this kernel, use:
[IPKernelApp] --existing kernel-6759.json
这写了'kernel-6759.json'文件
然后你可以运行这个 Python 片段来连接一个 KernelManager,并运行一些代码:
from IPython.lib.kernel import find_connection_file
from IPython.zmq.blockingkernelmanager import BlockingKernelManager
# this is a helper method for turning a fraction of a connection-file name
# into a full path. If you already know the full path, you can just use that
cf = find_connection_file('6759')
km = BlockingKernelManager(connection_file=cf)
# load connection info and init communication
km.load_connection_file()
km.start_channels()
def run_cell(km, code):
# now we can run code. This is done on the shell channel
shell = km.shell_channel
print
print "running:"
print code
# execution is immediate and async, returning a UUID
msg_id = shell.execute(code)
# get_msg can block for a reply
reply = shell.get_msg()
status = reply['content']['status']
if status == 'ok':
print 'succeeded!'
elif status == 'error':
print 'failed!'
for line in reply['content']['traceback']:
print line
run_cell(km, 'a=5')
run_cell(km, 'b=0')
run_cell(km, 'c=a/b')
运行的输出:
running:
a=5
succeeded!
running:
b=0
succeeded!
running:
c=a/b
failed!
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
/Users/minrk/<ipython-input-11-fb3f79bd285b> in <module>()
----> 1 c=a/b
ZeroDivisionError: integer division or modulo by zero
见 message spec有关如何解释回复的更多信息。如果相关,stdout/err 和显示数据将通过 km.iopub_channel
,您可以使用 shell.execute()
返回的 msg_id将输出与给定的执行相关联。
PS:对于这些新功能的文档质量,我深表歉意。我们有很多工作要做。
关于python - 连接到远程 IPython 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9977446/