traceback.print_stack():

>>> def f():
...   def g():
...     traceback.print_stack()
...   g()
...
>>> f()
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in f
  File "<stdin>", line 3, in g

Edit: You can also use extract_stack, take a slice (e.g. stack[5:] for exclude the first 5 levels) and use format_list to get a print-ready stacktrace ('\n'.join(traceback.format_list(...)))

Answer from user395760 on Stack Overflow
🌐
Sentry
sentry.io › sentry answers › python › print stack traces in python
Print stack traces in Python | Sentry
July 3, 2026 - The inspect.getinnerframes function returns a list of FrameInfo objects, each of which contains the details of a single frame in the stack trace, including the filename, line number, function, and code context. Inside the for loop, we retrieve each of these and then print them, using a format that mimics Python’s default stack trace printouts. Unlike traceback.print_exception, this approach gives us complete control over how the stack trace is printed.
Discussions

How can I use Try Except without hiding the stack trace?
repr doesn't give you all the info in the exception. Look at the traceback module for printing them more formatted with full stacktrace. Look at the rich package on PyPI if you want really fancy formatting and colors. More on reddit.com
🌐 r/pythontips
9
3
September 19, 2025
Catch and print full Python exception traceback without halting/exiting the program - Stack Overflow
I want to print the exact same ... the exception, and I do not want it to exit my program. ... Not a full answer, but someone might want to know that you can access lots of info looking into err.__traceback__ (at least in Python 3.x) ... It seems I'm the only one in the world who wants to print the stack when there's ... More on stackoverflow.com
🌐 stackoverflow.com
Print traceback without an exception
Hello, in CPython, there is a way to print a traceback outside of an exception, through traceback.print_stack() function. What would it take to add similar functionality to micropython? More on github.com
🌐 github.com
10
April 2, 2019
python - Print stacktrace without throwing exception - Stack Overflow
Explore Stack Internal ... Closed 12 years ago. I have inherited a large Python project in which there are points whereI want to know how I got there. So I would like to see a stracetrace. It seems that the traceback module can do that, but I need to throw an exception. More on stackoverflow.com
🌐 stackoverflow.com
January 31, 2014
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
What does a stack trace show?
A stack trace displays the call stack (set of active method calls) and provides information about the methods called before an error occurs. It helps developers to figure out what went wrong in the code.
🌐
scaler.com
scaler.com › home › topics › python program to print stack trace
Python Program to Print Stack Trace - Scaler Topics
🌐
Python
docs.python.org › 3 › library › traceback.html
traceback — Print or retrieve a stack traceback
Given a list of tuples or FrameSummary objects as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None. traceback.format_exception_only(exc, /, [value, ]*, show_group=False)¶
🌐
Reddit
reddit.com › r/pythontips › how can i use try except without hiding the stack trace?
r/pythontips on Reddit: How can I use Try Except without hiding the stack trace?
September 19, 2025 -

I've been dealing with legacy code that uses Try Excepts. The issue I'm having is that when a failure occurs the stack trace points to the line the Except is on (well the line below that's reporting it).

Code looks a little like this:

try:
  ...
except Exception as e:
  print(f"Error {str(repr(e))}")

Is this legacy code written incorrectly? Is there a reason we don't want to stack trace?

Maybe I'm wrong and this is returning the stacktrace but in a file that I'm not looking at, but I wanted to double check because so far Excepts seem to be a hidderance for me when I'm troubleshooting.

🌐
EyeHunts
tutorial.eyehunts.com › home › python print stack trace without exception
Python print stack trace without exception
December 29, 2022 - Use traceback.print_stack to print stack trace without exception In Python. This module provides a standard interface to extract, format and
🌐
Code-maven
python.code-maven.com › python-exceptions › exceptions › stack-trace
No need for exception to print Stack trace - Error and Exception handling in Python
import traceback def foo(): bar() def bar(): #print(traceback.extract_stack()) print(''.join(traceback.format_stack())) foo() print("done") # File "python/examples/other/print_stack_trace.py", line 10, in <module> # foo() # File "python/examples/other/print_stack_trace.py", line 4, in foo # bar() # File "python/examples/other/print_stack_trace.py", line 8, in bar # print(''.join(traceback.format_stack())) # # done ·
Find elsewhere
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!")
🌐
Delft Stack
delftstack.com › home › howto › python › python print stack trace
How to Print Stack Trace in Python | Delft Stack
March 11, 2025 - The traceback module is a built-in Python library that provides utilities for extracting, formatting, and printing stack traces. It’s an essential tool for any developer looking to gain insights into errors. Here’s how you can use it: import traceback def faulty_function(): return 1 / 0 try: faulty_function() except Exception: traceback.print_exc()
🌐
GitHub
github.com › micropython › micropython › issues › 4667
Print traceback without an exception · Issue #4667 · micropython/micropython
April 2, 2019 - Hello, in CPython, there is a way to print a traceback outside of an exception, through traceback.print_stack() function. What would it take to add similar functionality to micropython?
Author: micropython
🌐
Scaler
scaler.com › home › topics › python program to print stack trace
Python Program to Print Stack Trace - Scaler Topics
January 6, 2023 - The traceback module in Python provides functionalities to deal with the stack trace. The methods used to print stack trace are print_exception() and print_exc().
🌐
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 - By the end of this tutorial, you will be able to retrieve, read, print, and format a Python traceback. Learn online and earn valuable credentials from top universities like Yale, Michigan, Stanford, and leading companies like Google and IBM. Join ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-print-exception-stack-trace-in-python
How to Print Exception Stack Trace in Python - GeeksforGeeks
July 15, 2025 - In Python, when an exception occurs, a stack trace provides details about the error, including the function call sequence, exact line and exception type. This helps in debugging and identifying issues quickly. ... Let's explore different methods to achieve this. traceback.print_exc() is a simple ...
🌐
GitHub
gist.github.com › nepsilon › 107971fb4b65c9cea7c58cbdcea2abb6
Python: How to print the full traceback without exiting the program? — First published in fullweb.io issue #81
December 17, 2022 - — First published in fullweb.io issue #81 ... The exception handling block except Exception as ex: print(ex) will only print the exception message and not its traceback. That’s good to know, but we need more info than this to debug properly.
🌐
Python Module of the Week
pymotw.com › 3 › traceback
traceback — Exceptions and Stack Traces
March 18, 2018 - import traceback import sys from traceback_example import produce_exception print('with no exception:') exc_type, exc_value, exc_tb = sys.exc_info() tbe = traceback.TracebackException(exc_type, exc_value, exc_tb) print(''.join(tbe.format())) print('\nwith exception:') try: produce_exception() except Exception as err: exc_type, exc_value, exc_tb = sys.exc_info() tbe = traceback.TracebackException( exc_type, exc_value, exc_tb, ) print(''.join(tbe.format())) print('\nexception only:') print(''.join(tbe.format_exception_only())) The format() method produces a formatted version of the full tracebac
🌐
Python Module of the Week
pymotw.com › 2 › traceback
traceback – Extract, format, and print exceptions and stack traces. - Python Module of the Week
There are shorthand functions for printing the formatted values, as well. Although the functions in traceback mimic the behavior of the interactive interpreter by default, they also are useful for handling exceptions in situations where dumping the full stack trace to stderr is not desirable.
🌐
Bite Code
bitecode.dev › bite code! › why and how to hide the python stack trace
Why and how to hide the Python stack trace - Bite code!
January 15, 2024 - By default, sys.excepthook is set ... which prints the stack trace to the terminal, but you can replace this function by your own: import sys SHOW_STACK_TRACE = False def on_crash(exctype, value, traceback): # "exctype" is the class of the exception ...
🌐
SentinelOne
sentinelone.com › blog › data platform › python stack trace: understanding it and using it to debug
Python Stack Trace: Understanding it and Using it to Debug
October 27, 2022 - However, the Python stack trace ... a Python stack trace provides is vital to becoming a better Python programmer. In other words, a stack trace prints all the calls prior to the function that raised an exception....
🌐
Codemia
codemia.io › home › knowledge hub › catch and print full python exception traceback without halting/exiting the program
Catch and print full Python exception traceback without halting/exiting the program | Codemia
December 28, 2024 - To catch and print the exception without halting the program using standard library resources, you can use the traceback module, which provides utilities for extracting and formatting stack traces.