从iPython内核捕获语法错误



在进程内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)

我不得不修饰run_code来捕获它的结果并将其设置为self,因为_get_exc_info在发生另一个错误之前都会返回相同的错误,所以没有其他方法可以查看是否发生了错误。如果有人有更好的方法,我想听听。

在iptyhon 3.0中,错误情况更容易捕捉,请参阅此处。

最新更新