traceback.print_exc()的用法


Python使用traceback.print_exc()來代替print e 來輸出詳細的異常信息
 
[python] view plain copy
  1. try:  
  2.     1/0  
  3. except Exception,e:  
  4.     print e  
 
輸出結果是integer division or modulo by zero,只知道是報了這個錯,但是卻不知道在哪個文件哪個函數哪一行報的錯。
下面使用traceback模塊
 
[python] view plain copy
  1. import traceback  
  2. try:  
  3.     1/0  
  4. except Exception,e:  
  5.     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文件去。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM