6

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:
    last_exception = e
# this happens somewhere else, decoupled from the original raise
print_exception_stack_trace(last_exception)
Katriel
  • 120,462
  • 19
  • 136
  • 170
camillobruni
  • 2,298
  • 16
  • 26
  • possible duplicate of [How can you inspect the stack trace of an exception in Python?](http://stackoverflow.com/questions/2359248/how-can-you-inspect-the-stack-trace-of-an-exception-in-python) – David Webb Jul 29 '10 at 11:28
  • 1
    Well, yes, but that question isn't (satisfactorily) answered! – Katriel Jul 29 '10 at 11:31

1 Answers1

3

Edit: I lied, sorry. e.__traceback__ is what you want.

try:
    raise ValueError
except ValueError as e:
    print( e.__traceback__ )

>c:/python31/pythonw -u "test.py"
<traceback object at 0x00C964B8>
>Exit code: 0

This is only valid in Python 3; you can't do it in earlier versions.

Katriel
  • 120,462
  • 19
  • 136
  • 170