別のPythonプログラムのカーネルでコードを実行する場合、最も簡単な方法はBlockingKernelManagerに接続することです。現在のこの最良の例は、Paul Ivanovのvim-ipythonクライアント、またはIPython独自のターミナルクライアントです。
要旨:
- ipythonカーネルは
IPYTHONDIR/profile_<name>/security/kernel-<id>.json
、さまざまなクライアントが接続してコードを実行するために必要な情報を含むJSON接続ファイルをで書き込みます。
- KernelManagerは、カーネルとの通信(コードの実行、結果の受信など)に使用されるオブジェクトです。*
実例:
シェルで、次のことを行います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
応答の解釈方法の詳細については、メッセージ仕様を参照してください。必要に応じて、stdout / errおよびdisplayデータがkm.iopub_channel
渡され、によって返されたmsg_idを使用して、shell.execute()
出力を特定の実行に関連付けることができます。
PS:これらの新機能のドキュメントの品質についてお詫び申し上げます。やるべきことはたくさんあります。