Python使用traceback.print_exc()來代替print e 來輸出詳細的異常信息
[python] view plain copy
- try:
- 1/0
- except Exception,e:
- print e
輸出結果是integer division or modulo by zero,只知道是報了這個錯,但是卻不知道在哪個文件哪個函數哪一行報的錯。
下面使用traceback模塊
[python] view plain copy
- import traceback
- try:
- 1/0
- except Exception,e:
- traceback.print_exc()
輸出結果是
Traceback (most recent call last):
File "test_traceback.py", line 3, in <module>
1/0
ZeroDivisionError: integer division or modulo by zero
這樣非常直觀有利於調試。
traceback.print_exc()跟traceback.format_exc()有什么區別呢?
format_exc()返回字符串,print_exc()則直接給打印出來。
即traceback.print_exc()與print traceback.format_exc()效果是一樣的。
print_exc()還可以接受file參數直接寫入到一個文件。比如
traceback.print_exc(file=open('tb.txt','w+'))
寫入到tb.txt文件去。