如何在作为参数传递的函数异常后获得完整的堆栈跟踪?

时间:2016-01-10 21:43:04

标签: python

我有包装函数,它将其他函数作为参数,捕获异常并对其执行某些操作:

    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()本身的信息,而不包含任何更深层次的信息。是否有可能以及如何在此类呼叫后获得完整的堆栈跟踪?

2 个答案:

答案 0 :(得分:3)

import traceback

def a(x):
    b(x)

def b(x):
    x/0

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

回溯存储在字典中:

>>> 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

traceback module documentation

中的更多信息

答案 1 :(得分:0)

不确定这是否是您所需要的,但这些可能是您打印回溯的一种方式:

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

-OR -

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
>>>