2019-05-13 16:12:42 3911浏览
今天千锋扣丁学堂Python培训老师给大家分享一篇关于Python之traceback的具体使用方法详解,首先在之前做Java的时候,异常对象默认就包含stacktrace相关的信息,通过异常对象的相关方法printStackTrace()和getStackTrace()等方法就可以取到异常栈信息,能打印到log辅助调试或者做一些别的事情。但是到了Python,在2.x中,异常对象可以是任何对象,经常看到很多代码是直接raise一个字符串出来,因此就不能像Java那样方便的获取异常栈了,因为异常对象和异常栈是分开的。而多数Python语言的书籍上重点在于描述Python中如何构造异常对象和raisetryexceptfinally这些的使用,对调试程序起关键作用的stacktrace往往基本上不怎么涉及。
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
输出结果: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
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()
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
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}
logging.exception(ex) logging.error(ex, exc_info=1) # 指名输出栈踪迹, logging.exception的内部也是包了一层此做法 logging.critical(ex, exc_info=1) # 更加严重的错误级别
【关注微信公众号获取更多学习资料】 【扫码进入Python全栈开发免费公开课】