Kamilski81
Kamilski81

Reputation: 15107

How do I get the stack trace from an Exception Object in Python 2.7?

How can I get the full stack trace from the Exception object itself?

Consider the following code as reduced example of the problem:

last_exception = None
try:
    raise Exception('foo failed')
except Exception as e:
    print "Exception Stack Trace %s" % e

Upvotes: 8

Views: 3746

Answers (1)

Michael
Michael

Reputation: 9058

The stack trace itself is not stored in the exception object itself. However, you can print the stack trace of the last recent exception using sys.exc_info() and the traceback module. Example:

import sys
import traceback

try:
    raise Exception('foo failed')
except Exception as e:
    traceback.print_tb(*sys.exc_info())

If you do not want to display the stack trace immediately, it should be possible to store the return value of sys.exc_info() somewhere.

Upvotes: 5

Related Questions