インプロセスipythonカーネルを介して接続、実行、表示、エラーを表示する方法は次のとおりです
import re, sys, time, os
from StringIO import StringIO
from IPython.kernel.inprocess.blocking import BlockingInProcessKernelClient
from IPython.kernel.inprocess.manager import InProcessKernelManager
from IPython.kernel.inprocess.ipkernel import InProcessKernel
from IPython.core.interactiveshell import InteractiveShell
from IPython.utils.io import capture_output
def decorated_run_code(fn):
def new_run_code(*args, **kwargs):
res = fn(*args, **kwargs)
setattr(args[0], "last_known_outflag", res)
return res
return new_run_code
InteractiveShell.run_code = decorated_run_code(InteractiveShell.run_code)
km = InProcessKernelManager()
km.start_kernel()
kc = BlockingInProcessKernelClient(kernel=km.kernel)
kc.start_channels()
kc.shell_channel.execute('%pylab inline')
kernel = InProcessKernel()
ip = kernel.shell.get_ipython()
with capture_output() as io:
ip.run_cell(fail)
print "res", io.stdout
etype, value, tb = kernel.shell._get_exc_info(None)
print kernel.shell.last_known_outflag
if kernel.shell.last_known_outflag: print (etype, "/", value, "/", tb)
_get_exc_info は別のエラーが発生するまで同じエラーを返し、エラーが発生したかどうかを確認する他の方法がなかったため、その結果を取得してそれを自分自身に設定するために run_code を修飾する必要がありました。誰かがより良い方法を持っているなら、私はそれを聞きたいです。