如何在Python中打印异常对象的堆栈跟踪?
请注意,问题是不是关于LAST的打印堆栈跟踪。异常对象可以在过去的某个时间保存。
答案 0 :(得分:6)
这有点不方便,但是您可以使用traceback.print_exception
。给定异常ex
:
traceback.print_exception(type(ex), ex, ex.__traceback__)
示例:
import traceback
try:
1/0
except Exception as ex:
traceback.print_exception(type(ex), ex, ex.__traceback__)
# output:
# Traceback (most recent call last):
# File "untitled.py", line 4, in <module>
# 1/0
# ZeroDivisionError: division by zero
答案 1 :(得分:0)
您可以手动遍历__traceback__
属性以打印行和文件:
def function():
raise ValueError("flfkl")
try:
function()
except Exception as e:
traceback = e.__traceback__
while traceback:
print("{}: {}".format(traceback.tb_frame.f_code.co_filename,traceback.tb_lineno))
traceback = traceback.tb_next