traceback.format_exc() will yield more info if that's what you want.

import traceback

def do_stuff():
    raise Exception("test exception")

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())

This outputs:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    do_stuff()
  File "main.py", line 5, in do_stuff
    raise Exception("test exception")
Exception: test exception
Answer from volting on Stack Overflow
🌐
Python
docs.python.org › 3 › library › traceback.html
traceback — Print or retrieve a stack traceback
The optional limit argument has the same meaning as for print_tb(). If chain is true (the default), then chained exceptions (the __cause__ or __context__ attributes of the exception) will be printed as well, like the interpreter itself does when printing an unhandled exception. Changed in version 3.5: The etype argument is ignored and inferred from the type of value. Changed in version 3.10: The etype parameter has been renamed to exc and is now positional-only. traceback.print_exc(limit=None, file=None, chain=True)¶
🌐
Python Module of the Week
pymotw.com › 2 › traceback
traceback – Extract, format, and print exceptions and stack traces. - Python Module of the Week
import traceback import sys from traceback_example import produce_exception print 'print_exc() with no exception:' traceback.print_exc(file=sys.stdout) print try: produce_exception() except Exception, err: print 'print_exc():' traceback.print_exc(file=sys.stdout) print print 'print_exc(1):' traceback.print_exc(limit=1, file=sys.stdout) In this example, the file handle for sys.stdout is substituted so the informational and traceback messages are mingled correctly: $ python traceback_print_exc.py print_exc() with no exception: None print_exc(): Traceback (most recent call last): File "traceback_
People also ask

Which module is required for Python print stack trace?
Importing the `traceback` module helps to extract, format and print stack traces.
🌐
scaler.com
scaler.com › home › topics › python program to print stack trace
Python Program to Print Stack Trace - Scaler Topics
Top answer
1 of 16
1534

traceback.format_exc() will yield more info if that's what you want.

import traceback

def do_stuff():
    raise Exception("test exception")

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())

This outputs:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    do_stuff()
  File "main.py", line 5, in do_stuff
    raise Exception("test exception")
Exception: test exception
2 of 16
880

Some other answer have already pointed out the traceback module.

Please notice that with print_exc, in some corner cases, you will not obtain what you would expect. In Python 2.x:

import traceback

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_exc()

...will display the traceback of the last exception:

Traceback (most recent call last):
  File "e.py", line 7, in <module>
    raise TypeError("Again !?!")
TypeError: Again !?!

If you really need to access the original traceback one solution is to cache the exception infos as returned from exc_info in a local variable and display it using print_exception:

import traceback
import sys

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        exc_info = sys.exc_info()

        # do you usefull stuff here
        # (potentially raising an exception)
        try:
            raise TypeError("Again !?!")
        except:
            pass
        # end of useful stuff


    finally:
        # Display the *original* exception
        traceback.print_exception(*exc_info)
        del exc_info

Producing:

Traceback (most recent call last):
  File "t.py", line 6, in <module>
    raise TypeError("Oups!")
TypeError: Oups!

Few pitfalls with this though:

  • From the doc of sys_info:

    Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. [...] If you do need the traceback, make sure to delete it after use (best done with a try ... finally statement)

  • but, from the same doc:

    Beginning with Python 2.2, such cycles are automatically reclaimed when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.


On the other hand, by allowing you to access the traceback associated with an exception, Python 3 produce a less surprising result:

import traceback

try:
    raise TypeError("Oups!")
except Exception as err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_tb(err.__traceback__)

... will display:

  File "e3.py", line 4, in <module>
    raise TypeError("Oups!")
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-print-exception-stack-trace-in-python
How to Print Exception Stack Trace in Python - GeeksforGeeks
July 15, 2025 - Traceback (most recent call last): ... the detailed error traceback using traceback.print_exc(), helping in debugging by displaying where the error occurred....
🌐
GeeksforGeeks
geeksforgeeks.org › python › traceback-in-python
Traceback in Python - GeeksforGeeks
August 1, 2020 - # importing module import traceback # declaring array A = [1, 2, 3, 4] try: value = A[5] except: # printing stack trace traceback.print_exc() # out of try-except # this statement is to show that the program continues # normally after the exception is handled print("end of program") Output : Traceback (most recent call last): File "C:/Python27/van.py", line 8, in value = A[5] IndexError: list index out of range end of program >>>
🌐
Real Python
realpython.com › ref › stdlib › traceback
traceback | Python Standard Library – Real Python
The Python traceback module provides utilities for working with error tracebacks in Python programs. It’s particularly useful for debugging and error handling, as it allows you to capture and display the call stack of a program when an exception occurs. ... >>> import traceback >>> try: ... {"a": 1}["b"] ... except KeyError: ... traceback.print_exc() Traceback (most recent call last): ...
🌐
Jython
jython.org › jython-old-sites › docs › library › traceback.html
26.7. traceback — Print or retrieve a stack traceback — Jython v2.5.2 documentation
This simple example implements a basic read-eval-print loop, similar to (but less useful than) the standard Python interactive interpreter loop. For a more complete implementation of the interpreter loop, refer to the code module. ... print “Exception in user code:” print ‘-‘*60 traceback.print_exc(file=sys.stdout) print ‘-‘*60
Find elsewhere
🌐
Scaler
scaler.com › home › topics › python program to print stack trace
Python Program to Print Stack Trace - Scaler Topics
January 6, 2023 - In the following code snippet, the value of the denominator is set to 0 to view how Python print stack trace works. The traceback.print_exc() method in the except block prints the program's location, the line where the error was encountered, and the name and relevant information about the error.
🌐
Coursera
coursera.org › tutorials › how to print, read, and format a python traceback
How to Print, Read, and Format a Python Traceback | Coursera
March 10, 2023 - Python provides a traceback when an exception is raised. You can extract, format, and print stack traces with the Python traceback module.
🌐
Read the Docs
stackless.readthedocs.io › en › 2.7-slp › library › traceback.html
28.10. traceback — Print or retrieve a stack traceback — Stackless-Python 2.7.15 documentation
This simple example implements a basic read-eval-print loop, similar to (but less useful than) the standard Python interactive interpreter loop. For a more complete implementation of the interpreter loop, refer to the code module. import sys, traceback def run_user_code(envdir): source = raw_input(">>> ") try: exec source in envdir except: print "Exception in user code:" print '-'*60 traceback.print_exc(file=sys.stdout) print '-'*60 envdir = {} while 1: run_user_code(envdir)
🌐
Cracklogic
cracklogic.com › home › unlock the secrets of python tracebacks with format guide
Python tracebacks explained - Cracklogic
February 26, 2025 - ... This function directly prints the traceback to the console, mimicking the interpreter’s behavior.It is typically used for debugging purposes when you want to immediately see the traceback printed to the console. def divide(a, b): try: ...
🌐
Coderz Column
coderzcolumn.com › tutorials › python › traceback-how-to-extract-format-and-print-error-stack-traces-in-python
traceback - How to Extract, Format, and Print Error Stack Traces in Python by Sunny Solanki
January 14, 2021 - import traceback import random try: out = random.randint(-5,-10) except Exception as e: traceback.print_tb(e.__traceback__) File "<ipython-input-2-200195b56950>", line 5, in <module> out = random.randint(-5,-10) File "/home/sunny/anaconda3/lib/python3.7/random.py", line 222, in randint return self.randrange(a, b+1) File "/home/sunny/anaconda3/lib/python3.7/random.py", line 200, in randrange raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
🌐
CodeRivers
coderivers.org › blog › python-print-traceback-from-exception
Python Print Traceback from Exception: A Comprehensive Guide - CodeRivers
February 22, 2026 - The traceback.print_exc() function prints the full traceback of the most recent exception that has been caught, including the line numbers where the error occurred and the sequence of function calls. In real-world applications, it is often better to log tracebacks rather than just printing them.
🌐
One Two Bytes
onetwobytes.com › 2021 › 11 › 12 › print-stack-trace-python-exception
Printing Stack Traces in Python Exceptions: A Comprehensive Guide | One Two Bytes
February 6, 2024 - Here’s a step-by-step guide: ... try: processEvent() # Call the function that might raise an exception except Exception as e: print("Error encountered:", e) traceback.print_exc() # Print the detailed stack trace
🌐
Python
docs.python.org › 3.4 › library › traceback.html
29.9. traceback — Print or retrieve a stack traceback — Python 3.4.10 documentation
June 16, 2019 - This is useful when you want to print stack traces under program control, such as in a “wrapper” around the interpreter. The module uses traceback objects — this is the object type that is stored in the sys.last_traceback variable and returned as the third item from sys.exc_info().
🌐
TimOnWeb
timonweb.com › tim kamanin — a django/wagtail developer › python › how to print exception traceback in python
How to print exception traceback in Python ⚡ | TimOnWeb
January 30, 2021 - Here's how you can print the traceback of an error in Python: import traceback try: raise Boom('This is where our code blows') except Exception: # here's how you get a traceback output traceback_output = traceback.format_exc() # Now you can ...
🌐
Delft Stack
delftstack.com › home › howto › python › python print stack trace
How to Print Stack Trace in Python | Delft Stack
March 11, 2025 - How do I print a stack trace in Python? You can print a stack trace using the traceback module, typically with the traceback.print_exc() function within an exception handling block.