32

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

Note that the question is NOT about printing stack trace of LAST exception. Exception object may be saved at some distant point of time in the past.

Dims
  • 47,675
  • 117
  • 331
  • 600
  • 2
    Similar: https://stackoverflow.com/questions/3702675/how-to-print-the-full-traceback-without-halting-the-program – user202729 Oct 10 '18 at 14:48

2 Answers2

46

It's a bit inconvenient, but you can use traceback.print_exception. Given an exception 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
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
4

you can manually iterate through the __traceback__ attribute to print lines & files:

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
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219