[英]How to get python exception traceback in function
我有一個應該處理所有錯誤的函數:
def err(e):
import traceback
message = traceback.print_exc()
print(message)
if __name__ == "__main__":
try:
1/0 # just sample
except Exception as e:
err(e)
但它會返回一個簡短的錯誤,如下所示:
integer division or modulo by zero
但是我需要更多詳細信息( traceback
)來檢查錯誤。
你傳遞的例外,你的功能,所以為什么要使用traceback
,你有e
那里。 如果需要回溯,只需抓住e.__traceback__
traceback__:
import traceback
def err(e):
tb = e.__traceback__
# print traceback
traceback.print_tb(tb)
對於不依賴dunder的選項,可以使用sys.exc_info
並保留回溯:
import traceback, sys
def err(e):
*_, tb = sys.exc_info()
# print traceback
traceback.print_tb(tb)
根據python文檔:
traceback.print_exc([limit [,file]])
This is a shorthand for print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file). (In fact, it uses
sys.exc_info()以線程安全的方式而不是使用不推薦使用的變量來檢索相同的信息。)
您實際上所做的只是打印出1/0產生的錯誤消息
如果要打印出個性化的錯誤消息,可以執行以下操作:
if __name__ == "__main__":
try:
1/0 # just sample
except Exception as e:
print 'This is the error I am expecting'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.