2012-07-17 201 views
7

想我跑在交互的IPython一些代码,它会产生一个未捕获的异常,如:如何获取默认捕获的异常对象ipython异常处理程序?

In [2]: os.waitpid(1, os.WNOHANG) 
--------------------------------------------------------------------------- 
OSError         Traceback (most recent call last) 
<ipython-input-2-bacc7636b058> in <module>() 
----> 1 os.waitpid(1, os.WNOHANG) 

OSError: [Errno 10] No child processes 

此异常现由默认的IPython的异常处理程序截获并产生错误消息。是否有可能以某种方式提取被IPython捕获的异常对象?

我希望有相同的效果:

# Typing this into IPython prompt: 
try: 
    os.waitpid(1, os.WNOHANG) 
except Exception, exc: 
    pass 
# (now I can interact with "exc" variable) 

但我想它没有这个try/except样板。

回答

21

我觉得sys.last_value应该做的伎俩:

In [8]: 1/0 
--------------------------------------------------------------------------- 
ZeroDivisionError       Traceback (most recent call last) 

/home/ubuntu/<ipython console> in <module>() 

ZeroDivisionError: integer division or modulo by zero 

In [11]: sys.last_value 
Out[11]: ZeroDivisionError('integer division or modulo by zero',) 

如果你想要更有趣了这样的事情,检出traceback module,但可能不会IPython的内多大用处的。