2016-01-10 29 views
2

我有包裝的功能,這需要其他功能參數,捕獲異常,並做一些事情吧:如何獲取函數作爲參數傳遞的異常之後的完整堆棧跟蹤?

def exceptionCatchingWrapper(funcToCall,destForException,*args,**kwargs): 
    try: 
     r=funcToCall(*args,**kwargs) 
    except: 
     destForException["exc_info"]=sys.exc_info() 
    else: 
     return r 

我意識到,當一個異常被捕獲,從sys.exc_info()採取的堆棧跟蹤僅包含有關exceptionCatchingWrapper()本身並沒有更深層次。這種呼叫之後是否有可能以及如何獲得完整的堆棧跟蹤?

回答

3
import traceback 

def a(x): 
    b(x) 

def b(x): 
    x/0 

d = {} 
exceptionCatchingWrapper(a, d, 10) 

回溯存儲在詞典:在traceback module documentation

>>> traceback.print_tb(d['exc_info'][2] 
    File "<stdin>", line 3, in exceptionCatchingWrapper 
    File "<stdin>", line 2, in a 
    File "<stdin>", line 2, in b 

>>> traceback.print_exception(d['exc_info'][0],d['exc_info'][1],d['exc_info'][2]) 
Traceback (most recent call last): 
    File "<stdin>", line 3, in exceptionCatchingWrapper 
    File "<stdin>", line 2, in a 
    File "<stdin>", line 2, in b 
ZeroDivisionError: integer division or modulo by zero 

的更多信息。

+0

恥辱包在我身上。一切都好 – ardabro

0

不知道這是否是你所需要的,但這些可能是你可以打印回溯的方式:

import traceback 
try: 
    s += 1 #this doesnt exist yet 
except: 
    a = traceback.format_exc() 
    print a 

- 或 -

import traceback, sys 

def DummyFunc2(): 
    s += 1 #this doesnt exist yet 
def DummyFunc1(): 
    DummyFunc2() 

try: 
    DummyFunc1() 
except: 
    _, err, tb = sys.exc_info() 
    tb_lines = traceback.extract_tb(tb) 
    for idx, trace in enumerate(traceback.format_list(tb_lines)): 
     print "[INDEX %d]\n%s" % (idx,trace) 
    print err 

輸出:

>>> 
[INDEX 0] 
    File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 9, in <module> 
    DummyFunc1() 

[INDEX 1] 
    File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 6, in DummyFunc1 
    DummyFunc2() 

[INDEX 2] 
    File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 4, in DummyFunc2 
    s += 1 #this doesnt exist yet 

local variable 's' referenced before assignment 
>>> 
相關問題