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()進去看看實現
測試代碼如下:
def func(a, b):
return a / b
if __name__ == '__main__':
import sys
import time
import traceback
try:
func(1, 0)
except Exception as e:
print('***', type(e), e, '***')
time.sleep(2)
print("***traceback.print_exc():*** ")
time.sleep(1)
traceback.print_exc()
time.sleep(2)
print("***traceback.format_exc():*** ")
time.sleep(1)
print(traceback.format_exc())
time.sleep(2)
print("***traceback.print_exception():*** ")
time.sleep(1)
traceback.print_exception(*sys.exc_info())
運行結果:
*** <class 'ZeroDivisionError'> division by zero ***
***traceback.print_exc():***
Traceback (most recent call last):
File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module>
func(1, 0)
File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, in func
return a / b
ZeroDivisionError: division by zero
***traceback.format_exc():***
Traceback (most recent call last):
File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module>
func(1, 0)
File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, in func
return a / b
ZeroDivisionError: division by zero
***traceback.print_exception():***
Traceback (most recent call last):
File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module>
func(1, 0)
File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, in func
return a / b
ZeroDivisionError: division by zero
可以看出盅抚,三種方式打印結果是一樣的媳板。在開發(fā)時,做調試是很方便的泉哈。也可以把這種異常棧寫入日志蛉幸。
logging.exception(ex)
# 指名輸出棧蹤跡, logging.exception的內部也是包了一層此做法
logging.error(ex, exc_info=1)
# 更加嚴重的錯誤級別
logging.critical(ex, exc_info=1)
# 我直接copy的,未嘗試丛晦。有時間會試下的
python 還有一個模塊叫cgitb奕纫,輸出的error非常詳情。
try:
func(1, 0)
except Exception as e:
import cgitb
cgitb.enable(format='text')
func(1, 0)
參考:
https://blog.csdn.net/lengxingxing_/article/details/56317838