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

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

Leave a Comment

techhipbettruvabetnorabahisbahis forumu