2019-05-13 16:12:42 5084瀏覽
今天千鋒扣丁學(xué)堂Python培訓(xùn)老師給大家分享一篇關(guān)于Python之traceback的具體使用方法詳解,首先在之前做Java的時(shí)候,異常對(duì)象默認(rèn)就包含stacktrace相關(guān)的信息,通過(guò)異常對(duì)象的相關(guān)方法printStackTrace()和getStackTrace()等方法就可以取到異常棧信息,能打印到log輔助調(diào)試或者做一些別的事情。但是到了Python,在2.x中,異常對(duì)象可以是任何對(duì)象,經(jīng)??吹胶芏啻a是直接raise一個(gè)字符串出來(lái),因此就不能像Java那樣方便的獲取異常棧了,因?yàn)楫惓?duì)象和異常棧是分開(kāi)的。而多數(shù)Python語(yǔ)言的書(shū)籍上重點(diǎn)在于描述Python中如何構(gòu)造異常對(duì)象和raisetryexceptfinally這些的使用,對(duì)調(diào)試程序起關(guān)鍵作用的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
輸出結(jié)果: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的內(nèi)部也是包了一層此做法 logging.critical(ex, exc_info=1) # 更加嚴(yán)重的錯(cuò)誤級(jí)別
【關(guān)注微信公眾號(hào)獲取更多學(xué)習(xí)資料】 【掃碼進(jìn)入Python全棧開(kāi)發(fā)免費(fèi)公開(kāi)課】
查看更多關(guān)于"Python開(kāi)發(fā)資訊"的相關(guān)文章>