2012-07-17 87 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的內多大用處的。