關于Python異常處理方面的一些基礎知識。
之前在做Java的時候,異常對象默認就包含stacktrace相關的信息,通過異常對象的相關方法printStackTrace()和getStackTrace()等方法就可以取到異常棧信息,能打印到log輔助調試或者做一些別的事情。但是到了Python,在2.x中,異常對象可以是任何對象,經常看到很多代碼是直接raise一個字符串出來,因此就不能像Java那樣方便的獲取異常棧了,因為異常對象和異常棧是分開的。而多數Python語言的書籍上重點在于描述Python中如何構造異常對象和raise try except finally這些的使用,對調試程序起關鍵作用的stacktrace往往基本上不怎么涉及。
python中用于處理異常棧的模塊是traceback模塊,它提供了print_exception、format_exception等輸出異常棧等常用的工具函數。
1 2 3 4 5 6 7 8 9 10 | 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) |
輸出結果:
1 2 3 4 5 6 | 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()函數得到的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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) |
輸出結果:
1 2 3 4 5 6 7 8 9 10 | 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對象所包含的數據:
1 2 3 4 5 6 7 8 9 10 11 | 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) |
輸出結果:
1 2 3 | samchimac:tracebacktest samchi$ python . /teststacktrace .py . /teststacktrace .py :7 'func(1, 0)' in <module>() . /teststacktrace .py :2 'return a / b' in func() |
如果平時開發喜歡基于log的方式來調試,那么可能經常去做這樣的事情,在log里面發現異常之后,因為信息不足,那么會再去額外加一些debug log來把相關變量的值輸出。調試完畢之后再把這些debug log去掉。其實沒必要這么麻煩,Python庫中提供了cgitb模塊來幫助做這些事情,它能夠輸出異常上下文所有相關變量的信息,不必每次自己再去手動加debug log。
cgitb的使用簡單的不能想象:
1 2 3 4 5 6 7 8 | def func(a, b): return a / b if __name__ = = '__main__' : import cgitb cgitb.enable( format = 'text' ) import sys import traceback func( 1 , 0 ) |
運行之后就會得到詳細的數據:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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是一個默認的全局異常攔截器,可以嘗試去自行對它修改:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 ) |
輸出結果:
1 2 3 4 5 | 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 } |
看到沒有?沒有什么神奇的東西,只是從stack frame對象中獲取的相關變量的值。frame對象中還有很多神奇的屬性,就不一一探索了。
在使用Java的時候,用log4j記錄異常很簡單,只要把Exception對象傳遞給log.error方法就可以了,但是在Python中就不行了,如果直接傳遞異常對象給log.error,那么只會在log里面出現一行異常對象的值。
在Python中正確的記錄Log方式應該是這樣的:
1 2 3 | logging.exception(ex) logging.error(ex, exc_info = 1 ) # 指名輸出棧蹤跡, logging.exception的內部也是包了一層此做法 logging.critical(ex, exc_info = 1 ) # 更加嚴重的錯誤級別 |
新聞熱點
疑難解答