搞清楚 Python traceback的具體使用方法
1. Python中的異常棧跟蹤
之前在做Java的時(shí)候,異常對(duì)象默認(rèn)就包含stacktrace相關(guān)的信息,通過異常對(duì)象的相關(guān)方法printStackTrace()和getStackTrace()等方法就可以取到異常棧信息,能打印到log輔助調(diào)試或者做一些別的事情。但是到了Python,在2.x中,異常對(duì)象可以是任何對(duì)象,經(jīng)??吹胶芏啻a是直接raise一個(gè)字符串出來,因此就不能像Java那樣方便的獲取異常棧了,因?yàn)楫惓?duì)象和異常棧是分開的。而多數(shù)Python語言的書籍上重點(diǎn)在于描述Python中如何構(gòu)造異常對(duì)象和raise try except finally這些的使用,對(duì)調(diào)試程序起關(guān)鍵作用的stacktrace往往基本上不怎么涉及。
python中用于處理異常棧的模塊是traceback模塊,它提供了print_exception、format_exception等輸出異常棧等常用的工具函數(shù)。
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)
輸出結(jié)果:
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
其實(shí)traceback.print_exc()函數(shù)只是traceback.print_exception()函數(shù)的一個(gè)簡(jiǎn)寫形式,而它們獲取異常相關(guān)的數(shù)據(jù)都是通過sys.exc_info()函數(shù)得到的。
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)
輸出結(jié)果:
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()返回的值是一個(gè)元組,其中第一個(gè)元素,exc_type是異常的對(duì)象類型,exc_value是異常的值,exc_tb是一個(gè)traceback對(duì)象,對(duì)象中包含出錯(cuò)的行數(shù)、位置等數(shù)據(jù)。然后通過print_exception函數(shù)對(duì)這些異常數(shù)據(jù)進(jìn)行整理輸出。
traceback模塊提供了extract_tb函數(shù)來更加詳細(xì)的解釋traceback對(duì)象所包含的數(shù)據(jù):
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)
輸出結(jié)果:
samchimac:tracebacktest samchi$ python ./teststacktrace.py
./teststacktrace.py :7 'func(1, 0)' in <module>()
./teststacktrace.py :2 'return a / b' in func()
2. 使用cgitb來簡(jiǎn)化異常調(diào)試
如果平時(shí)開發(fā)喜歡基于log的方式來調(diào)試,那么可能經(jīng)常去做這樣的事情,在log里面發(fā)現(xiàn)異常之后,因?yàn)樾畔⒉蛔?,那么?huì)再去額外加一些debug log來把相關(guān)變量的值輸出。調(diào)試完畢之后再把這些debug log去掉。其實(shí)沒必要這么麻煩,Python庫中提供了cgitb模塊來幫助做這些事情,它能夠輸出異常上下文所有相關(guān)變量的信息,不必每次自己再去手動(dòng)加debug log。
cgitb的使用簡(jiǎn)單的不能想象:
def func(a, b): return a / b if __name__ == '__main__': import cgitb cgitb.enable(format='text') import sys import traceback func(1, 0)
運(yùn)行之后就會(huì)得到詳細(xì)的數(shù)據(jù):
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)了,個(gè)人感覺cgitb在線上環(huán)境不適合使用,適合在開發(fā)的過程中進(jìn)行調(diào)試,非常的方便。
也許你會(huì)問,cgitb為什么會(huì)這么屌?能獲取這么詳細(xì)的出錯(cuò)信息?其實(shí)它的工作原理同它的使用方式一樣的簡(jiǎn)單,它只是覆蓋了默認(rèn)的sys.excepthook函數(shù),sys.excepthook是一個(gè)默認(rèn)的全局異常攔截器,可以嘗試去自行對(duì)它修改:
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)
輸出結(jié)果:
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}
看到?jīng)]有?沒有什么神奇的東西,只是從stack frame對(duì)象中獲取的相關(guān)變量的值。frame對(duì)象中還有很多神奇的屬性,就不一一探索了。
3. 使用logging模塊來記錄異常
在使用Java的時(shí)候,用log4j記錄異常很簡(jiǎn)單,只要把Exception對(duì)象傳遞給log.error方法就可以了,但是在Python中就不行了,如果直接傳遞異常對(duì)象給log.error,那么只會(huì)在log里面出現(xiàn)一行異常對(duì)象的值。
在Python中正確的記錄Log方式應(yīng)該是這樣的:
logging.exception(ex) logging.error(ex, exc_info=1) # 指名輸出棧蹤跡, logging.exception的內(nèi)部也是包了一層此做法 logging.critical(ex, exc_info=1) # 更加嚴(yán)重的錯(cuò)誤級(jí)別
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python traceback模塊獲取異常信息的使用
- 解決python問題 Traceback (most recent call last)
- python如何利用traceback獲取詳細(xì)的異常信息
- Python基于traceback模塊獲取異常信息
- 淺談python出錯(cuò)時(shí)traceback的解讀
- Python 輸出詳細(xì)的異常信息(traceback)方式
- python3 使用traceback定位異常實(shí)例
- 基于python traceback實(shí)現(xiàn)異常的獲取與處理
- Python異常模塊traceback用法實(shí)例分析
- Python中使用logging和traceback模塊記錄日志和跟蹤異常
- 淺談Python traceback的優(yōu)雅處理
- python traceback捕獲并打印異常的方法
- Python?Traceback(most?recent?call?last)報(bào)錯(cuò)信息:示例解讀
相關(guān)文章
零基礎(chǔ)寫python爬蟲之使用Scrapy框架編寫爬蟲
前面的文章我們介紹了Python爬蟲框架Scrapy的安裝與配置等基本資料,本文我們就來看看如何使用Scrapy框架方便快捷的抓取一個(gè)網(wǎng)站的內(nèi)容,隨便選個(gè)小站(dmoz.org)來示例吧2014-11-11pytest官方文檔解讀fixtures調(diào)用fixtures及fixture復(fù)用性
這篇文章主要為大家介紹了pytest官方文檔解讀fixtures調(diào)用fixtures及fixture復(fù)用性,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06解決Tensorflow使用pip安裝后沒有model目錄的問題
今天小編就為大家分享一篇解決Tensorflow使用pip安裝后沒有model目錄的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06在Python中移動(dòng)目錄結(jié)構(gòu)的方法
這篇文章主要介紹了在Python中移動(dòng)目錄結(jié)構(gòu)的方法,需要的朋友可以參考下2016-01-01Python中標(biāo)準(zhǔn)模塊importlib詳解
這篇文章主要給大家詳細(xì)介紹了Python中標(biāo)準(zhǔn)模塊importlib的使用方法和示例,非常簡(jiǎn)單,有需要的小伙伴可以參考下2017-04-04python 如何把classification_report輸出到csv文件
這篇文章主要介紹了python 把classification_report輸出到csv文件的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05