Python 如何从作为参数传递的函数中获取异常后的完整堆栈跟踪?
我有一个包装器函数,它将其他函数作为参数,捕获异常并对其进行处理:Python 如何从作为参数传递的函数中获取异常后的完整堆栈跟踪?,python,Python,我有一个包装器函数,它将其他函数作为参数,捕获异常并对其进行处理: def exceptionCatchingWrapper(funcToCall,destForException,*args,**kwargs): try: r=funcToCall(*args,**kwargs) except: destForException["exc_info"]=sys.exc_info() else: return r
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()
本身的信息,没有更深的信息。在这样的调用之后,是否可能以及如何获得完整的堆栈跟踪
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
>>回溯。打印tb(d['exc\u info'][2]
文件“”,第3行,在例外的CatchingWrapper中
文件“”,第2行,在
文件“”,第2行,在b中
>>>回溯.打印异常(d['exc_信息'][0],d['exc_信息'][1],d['exc_信息'][2])
回溯(最近一次呼叫最后一次):
文件“”,第3行,在例外的CatchingWrapper中
文件“”,第2行,在
文件“”,第2行,在b中
ZeroDivisionError:整数除法或模零除法
有关详细信息,请参阅。不确定这是否是您所需要的,但这可能是您打印回溯的一种方式:
import traceback
try:
s += 1 #this doesnt exist yet
except:
a = traceback.format_exc()
print a
-或-
输出:
>>>
[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
>>>
>
[索引0]
文件“C:/Python27/Lib/site packages/xy/printrace.py”,第9行,在
DummyFunc1()
[索引1]
文件“C:/Python27/Lib/site packages/xy/printrace.py”,第6行,在DummyFunc1中
DummyFunc2()
[索引2]
文件“C:/Python27/Lib/site packages/xy/printtrace.py”,第4行,在DummyFunc2中
s+=1#这还不存在
赋值前引用的局部变量
>>>
我真丢脸,一切都好
>>>
[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
>>>