【问题标题】:Catching Syntax Errors from iPython Kernel从 iPython 内核捕获语法错误
【发布时间】:2013-12-03 08:50:18
【问题描述】:

inprocess 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 会返回相同的错误,直到发生另一个错误,因此没有其他方法可以查看是否发生错误。如果有人有更好的方法,我想听听。

【问题讨论】:

    标签: ipython ipython-notebook ipython-magic


    【解决方案1】:

    在 iptyhon 3.0 中更容易捕获错误条件,请参阅here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多