捕捉traceback异常栈信息
相关函数简介
sys.exc_info()
返回包含3个元素(type, value, traceback)的元组,提供关于当前正被处理的异常信息。如果异常没有被处理,返回包含3个None值的元组。
type:存放异常类型(类对象);
Value:获取异常参数(关联的值,或者需要抛出的第二个参数--总是异常类型是个类对象,那该参数总是一个异常类实例)(its associated value or the second argument to raise, which is always a class instance if the exception type is a class object);
traceback:获取traceback对象,记录异常发生点(根源)。
注意:把traceback值赋值给正在处理当前异常的函数中的本地变量,会引发循环引用问题,会影响垃圾回收。用完后需要删除。
参考连接:
https://docs.python.org/2/library/sys.html#sys.exc_info
traceback.extract_stack()
从stack frame提取原始的traceback
参考连接:
https://hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l280
代码演示
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
import sys
import traceback
def testfn():
# 定义异常信息模版
traceback_template = '''Traceback (most recent call last):
File "%(filename)s", line %(lineno)s, in %(name)s
%(type)s: %(message)s\n'''
try:
var = 5
assert var >0, 'var is larger than zero'
assert var % 2 == 0, 'var is not an even number'
except AssertionError:
exc_type, exc_value, exc_traceback = sys.exc_info()
print('异常类型:', exc_type)
print('关联的值,或者需要raise的第二个参数:', exc_value)
print('异常发生点(根源):', exc_traceback)
print('--------------------------')
traceback_details = {
'filename': exc_traceback.tb_frame.f_code.co_filename, #文件名
'lineno' : exc_traceback.tb_lineno, # 发生异常的行数
'name' : exc_traceback.tb_frame.f_code.co_name, # 所在函数
'type' : exc_type.__name__, # 异常类型
'message' : exc_value
}
traceback_info = traceback_template % traceback_details
print(traceback_info)
print('--------------------------')
raw_traceback = traceback.extract_stack()
print(raw_traceback)
finally: # 为避免垃圾回收问题需要删除
del (exc_type, exc_value, exc_traceback)
testfn()
运行结果
"D:\Program Files\python33\python.exe" E:/Projects/interface_project_for_dev/teststudy.py
异常类型:
关联的值,或者需要raise的第二个参数: var is not an even number
异常发生点(根源):
--------------------------
Traceback (most recent call last):
File "E:/Projects/interface_project_for_dev/teststudy.py", line 17, in testfn
AssertionError: var is not an even number
--------------------------
[('E:/Projects/interface_project_for_dev/teststudy.py', 44, '', 'testfn()'), ('E:/Projects/interface_project_for_dev/teststudy.py', 39, 'testfn', 'raw_traceback = traceback.extract_stack()')]
Process finished with exit code 0