python traceback捕獲並打印異常


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

  可以看出,三種方式打印結果是一樣的。在開發時,做調試是很方便的。也可以把這種異常棧寫入日志。

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)
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文件去。

 

參考:
https://blog.csdn.net/lengxingxing_/article/details/56317838


免責聲明!

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



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