Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 962
Kamilski81 Avatar asked Jul 08 '11 15:07

Kamilski81


People also ask

How do you capture a stack trace in Python?

Print Stack Trace in Python Using traceback Module The traceback. format_exc() method returns a string that contains the information about exception and stack trace entries from the traceback object. We can use the format_exc() method to print the stack trace with the try and except statements.

How do I get exception details in Python?

Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

What is stack trace in exception?

A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs. The StackTrace property returns the frames of the call stack that originate at the location where the exception was thrown.


1 Answers

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.

like image 71
Michael Avatar answered Oct 02 '22 23:10

Michael