test.py
#encoding:utf-8
import sys
import traceback
def testerr():
testerr2()
def testerr2():
a = "test"
b = 123
print(c) #不存在的变量,触发个异常
try:
testerr()
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
frame = traceback.extract_tb(exc_traceback) #返回一个异常栈的FrameSummary对象
#格式化成字符串输出
mapStack = map(str, frame)
sErrorStack = "\n".join(mapStack)
#也可以直接用traceback.format_exc()获取栈字符串
print("异常栈:")
print(sErrorStack)
#输出异常原因
print(repr(e))
#输出报错函数的局部变量
lasttb = None
while exc_traceback:
lasttb = exc_traceback
exc_traceback = exc_traceback.tb_next
print("局部变量:")
print(lasttb.tb_frame.f_locals)
输出结果:
异常栈:
NameError(“name ‘c’ is not defined”)
局部变量:
{‘a’: ‘test’, ‘b’: 123}
from functools import wraps
import sys
import traceback
def FormatError(func):
@wraps(func)
def Format(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
frame = traceback.extract_tb(exc_traceback) #返回一个异常栈的FrameSummary对象
#格式化成字符串输出
mapStack = map(str, frame)
sErrorStack = "\n".join(mapStack)
print("异常栈:")
print(sErrorStack)
#输出异常原因
print(repr(e))
#输出报错函数的局部变量
lasttb = None
while exc_traceback:
lasttb = exc_traceback
exc_traceback = exc_traceback.tb_next
print("局部变量:")
print(lasttb.tb_frame.f_locals)
return Format
@FormatError
def testerr():
testerr2()
def testerr2():
a = "test"
b = 123
print(c) #不存在的变量,触发个异常
testerr()