Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 236
camillobruni Avatar asked Nov 06 '22 10:11

camillobruni


1 Answers

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.

like image 180
Katriel Avatar answered Nov 11 '22 05:11

Katriel