Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 556
Dims Avatar asked Oct 10 '18 14:10

Dims


People also ask

How do I print a stack trace error?

The printStackTrace() method of Java. lang. Throwable class used to print this Throwable along with other details like class name and line number where the exception occurred means its backtrace. This method prints a stack trace for this Throwable object on the standard error output stream.

How do I print exception details in Python?

To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e . You can now print the error message with "print(e)" or use it for further processing.

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.

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.


2 Answers

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 
like image 72
Aran-Fey Avatar answered Sep 18 '22 03:09

Aran-Fey


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 
like image 45
Jean-François Fabre Avatar answered Sep 18 '22 03:09

Jean-François Fabre