简体   繁体   English

如何在Python中打印异常对象的堆栈跟踪?

[英]How to print the stack trace of an exception object in Python?

How to print the stack trace of an exception object in Python? 如何在Python中打印异常对象的堆栈跟踪?

Note that the question is NOT about printing stack trace of LAST exception. 请注意,问题不在于打印LAST异常的堆栈跟踪 Exception object may be saved at some distant point of time in the past. 可以在过去的某个遥远时间点保存异常对象。

It's a bit inconvenient, but you can use traceback.print_exception . 这有点不方便,但您可以使用traceback.print_exception Given an exception ex : 给定一个例外ex

traceback.print_exception(type(ex), ex, ex.__traceback__)

Example: 例:

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

you can manually iterate through the __traceback__ attribute to print lines & files: 您可以手动遍历__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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM