traceback模塊被用來跟蹤異常返回信息. 如下例所示:
1 2 3 4 5 | import traceback try : raise SyntaxError, "traceback test" except : traceback.print_exc() |
將會在控制臺輸出類似結果:
1 2 3 4 | Traceback (most recent call last): File "H:/PythonWorkSpace/Test/src/TracebackTest.py", line 3, in <module> raise SyntaxError, "traceback test" SyntaxError: traceback test |
類似在你沒有捕獲異常時候, 解釋器所返回的結果.
你也可以傳入一個文件, 把返回信息寫到文件中去, 如下:
1 2 3 4 5 6 7 8 9 | import traceback import StringIO try : raise SyntaxError, "traceback test" except : fp = StringIO.StringIO() #創建內存文件對象 traceback.print_exc( file = fp) message = fp.getvalue() print message |
這樣在控制臺輸出的結果和上面例子一樣,traceback模塊還提供了extract_tb函數來格式化跟蹤返回信息, 得到包含錯誤信息的列表, 如下:
1 2 3 4 5 6 7 8 9 10 11 12 | import traceback import sys def tracebacktest(): raise SyntaxError, "traceback test" try : tracebacktest() except : info = sys.exc_info() for file , lineno, function, text in traceback.extract_tb(info[ 2 ]): print file , "line:" , lineno, "in" , function print text print "** %s: %s" % info[: 2 ] |
控制臺輸出結果如下:
1 2 3 4 5 | H:/PythonWorkSpace/Test/src/TracebackTest.py line: 7 in <module> tracebacktest() H:/PythonWorkSpace/Test/src/TracebackTest.py line: 5 in tracebacktest raise SyntaxError, "traceback test" ** <type 'exceptions.SyntaxError'>: traceback test |
test1.py中,當分母為0的時候,調用系統退出。代碼如下:
1 2 3 4 5 6 7 8 | #!/usr/bin/python import sys def division(a = 1 , b = 1 ): if b = = 0 : print 'b eq 0' sys.exit( 1 ) else : return a / b |
test2.py中,用try..except捕獲異常,然后traceback.print_exc()打印。
代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 | #!/usr/bin/python import sys import traceback import test1 a = 10 b = 0 try : print test1.division(a,b) except : print 'invoking division failed.' traceback.print_exc() sys.exit( 1 ) |
執行test2.py失敗拋出異常。
1 2 3 4 5 6 7 8 9 10 | $python test2.py execution python-2.5.1/python (enodeb/linux) b eq 0 invoking division failed. Traceback (most recent call last): File "test2.py", line 10, in <module> test1.division(a,b) File "/home/fesu/test1.py", line 6, in division sys.exit(1) SystemExit: 1 |
新聞熱點
疑難解答