Python traceback【转】

1. Python中的异常栈跟踪

Python,在2.x中,异常对象可以是任何对象,异常对象和异常栈是分开的。
python中用于处理异常栈的模块是traceback模块,它提供了print_exception、format_exception等输出异常栈等常用的工具函数。

 def func(a, b):
return a / b
if __name__ == '__main__':
import sys
import traceback
try:
func(1, 0)
except Exception as e:
print "print exc"
traceback.print_exc(file=sys.stdout)

输出结果:

 print exc
Traceback (most recent call last):
File "./teststacktrace.py", line 7, in <module>
func(1, 0)
File "./teststacktrace.py", line 2, in func
return a / b

其实traceback.print_exc()函数只是traceback.print_exception()函数的一个简写形式,而它们获取异常相关的数据都是通过sys.exc_info()函数得到的。

 def func(a, b):
return a / b
if __name__ == '__main__':
import sys
import traceback
try:
func(1, 0)
except Exception as e:
print "print_exception()"
exc_type, exc_value, exc_tb = sys.exc_info()
print 'the exc type is:', exc_type
print 'the exc value is:', exc_value
print 'the exc tb is:', exc_tb
traceback.print_exception(exc_type, exc_value, exc_tb)

输出结果:

 print_exception()
the exc type is: <type 'exceptions.ZeroDivisionError'>
the exc value is: integer division or modulo by zero
the exc tb is: <traceback object at 0x104e7d4d0>
Traceback (most recent call last):
File "./teststacktrace.py", line 7, in <module>
func(1, 0)
File "./teststacktrace.py", line 2, in func
return a / b
ZeroDivisionError: integer division or modulo by zero

sys.exc_info()返回的值是一个元组,其中第一个元素,exc_type是异常的对象类型,exc_value是异常的值,exc_tb是一个 traceback对象,对象中包含出错的行数、位置等数据。然后通过print_exception函数对这些异常数据进行整理输出。

traceback模块提供了extract_tb函数来更加详细的解释traceback对象所包含的数据:

 def func(a, b):
return a / b
if __name__ == '__main__':
import sys
import traceback
try:
func(1, 0)
except:
_, _, exc_tb = sys.exc_info()
for filename, linenum, funcname, source in traceback.extract_tb(exc_tb):
print "%-23s:%s '%s' in %s()" % (filename, linenum, source, funcname)

输出结果:

 samchimac:tracebacktest samchi$ python ./teststacktrace.py
./teststacktrace.py :7 'func(1, 0)' in <module>()
./teststacktrace.py :2 'return a / b' in func()

2. 使用cgitb来简化异常调试

如果平时开发喜欢基于log的方式来调试,那么可能经常去做这样的事情,在log里面发现异常之后,因为信息不足,那么会再去额外加一些debug log来把相关变量的值输出。调试完毕之后再把这些debug log去掉。其实没必要这么麻烦,Python库中提供了cgitb模块来帮助做这些事情,它能够输出异常上下文所有相关变量的信息,不必每次自己再去手动加debug log。

cgitb的使用简单的不能想象:

 def func(a, b):
return a / b
if __name__ == '__main__':
import cgitb
cgitb.enable(format='text')
import sys
import traceback
func(1, 0)

运行之后就会得到详细的数据:

 A problem occurred in a Python script.  Here is the sequence of
function calls leading up to the error, in the order they occurred. /Users/samchi/Documents/workspace/tracebacktest/teststacktrace.py in <module>()
4 import cgitb
5 cgitb.enable(format='text')
6 import sys
7 import traceback
8 func(1, 0)
func = <function func> /Users/samchi/Documents/workspace/tracebacktest/teststacktrace.py in func(a=1, b=0)
2 return a / b
3 if __name__ == '__main__':
4 import cgitb
5 cgitb.enable(format='text')
6 import sys
a = 1
b = 0

完全不必再去log.debug("a=%d" % a)了,个人感觉cgitb在线上环境不适合使用,适合在开发的过程中进行调试,非常的方便。

也许你会问,cgitb为什么会这么屌?能获取这么详细的出错信息?其实它的工作原理同它的使用方式一样的简单,它只是覆盖了默认的sys.excepthook函数,sys.excepthook是一个默认的全局异常拦截器,可以尝试去自行对它修改:

 def func(a, b):
return a / b
def my_exception_handler(exc_type, exc_value, exc_tb):
print "i caught the exception:", exc_type
while exc_tb:
print "the line no:", exc_tb.tb_lineno
print "the frame locals:", exc_tb.tb_frame.f_locals
exc_tb = exc_tb.tb_next if __name__ == '__main__':
import sys
sys.excepthook = my_exception_handler
import traceback
func(1, 0)

输出结果:

 i caught the exception: <type 'exceptions.ZeroDivisionError'>
the line no: 14
the frame locals: {'my_exception_handler': <function my_exception_handler at 0x100e04aa0>, '__builtins__': <module '__builtin__' (built-in)>, '__file__': './teststacktrace.py', 'traceback': <module 'traceback' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.pyc'>, '__package__': None, 'sys': <module 'sys' (built-in)>, 'func': <function func at 0x100e04320>, '__name__': '__main__', '__doc__': None}
the line no: 2
the frame locals: {'a': 1, 'b': 0}

3. 使用logging模块来记录异常

在使用Java的时候,用log4j记录异常很简单,只要把Exception对象传递给log.error方法就可以了,但是在Python中就不行了,如果直接传递异常对象给log.error,那么只会在log里面出现一行异常对象的值。

在Python中正确的记录Log方式应该是这样的:

 logging.exception(ex)
logging.error(ex, exc_info=1) # 指名输出栈踪迹, logging.exception的内部也是包了一层此做法
logging.critical(ex, exc_info=1) # 更加严重的错误级别

转自:http://my.oschina.net/chihz/blog/180573

上一篇:scala中集合的交集、并集、差集


下一篇:Scala(四)【集合基础入门】