1、traceback.print_exc()
2、traceback.format_exc()
3、traceback.print_exception()
簡單說下這三個方法是做什么用的:
1、print_exc():是對異常棧輸出 2、format_exc():是把異常棧以字符串的形式返回,print(traceback.format_exc()) 就相當於traceback.print_exc() 3、print_exception():traceback.print_exc()實現方式就是traceback.print_exception(sys.exc_info()),可以點sys.exc_info()進去看看實現
問題: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文件去。
traceback.print_exc([limit[, file]])
print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)的簡寫
import traceback def abc(): try: 1/0 except Exception as e: traceback.print_exc() if __name__ == '__main__': abc()
1/0
ZeroDivisionError: division by zero
traceback.format_exc([limit])
類似於print_exc(limit), 但是返回字符串而不是輸出到file.
import traceback try: raise ValueError("msg") except Exception as e: print(traceback.format_exc())
raise ValueError("msg") ValueError: msg
traceback.print_exc()函數只是traceback.print_exception()函數的一個簡寫形式,而它們獲取異常相關的數據都是通過sys.exc_info()函數得到的。
import sys import traceback def func(a, b): return a / b if __name__ == '__main__': 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)
返回結果
print_exception() Traceback (most recent call last): the exc type is: <class 'ZeroDivisionError'> File , line 16, in <module> the exc value is: division by zero func(1, 0) the exc tb is: <traceback object at 0x000002583038D188> File , line 12, in func return a / b ZeroDivisionError: division by zero
sys.exc_info()返回的值是一個元組,其中第一個元素,exc_type是異常的對象類型,exc_value是異常的值,exc_tb是一個traceback對象,對象中包含出錯的行數、位置等數據。
然后通過print_exception函數對這些異常數據進行整理輸出。
三種方式打印結果是一樣的。在開發時,做調試是很方便的。也可以把這種異常棧寫入日志。
logging.exception(ex) # 指名輸出棧蹤跡, logging.exception的內部也是包了一層此做法 logging.error(ex, exc_info=1) # 更加嚴重的錯誤級別 logging.critical(ex, exc_info=1)