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
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 = input(">>> ") try: exec(source, envdir) except Exception: print("Exception in user code:") print("-"*60) traceback.print_exc(file=sys.stdout) print("-"*60) envdir = {} while True: run_user_code(envdir)
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!")
Discussions

python - Why do I have to import traceback if it already exists? - Stack Overflow
If I write something in Python and things go awry, I automatically get a traceback. For example: #!/usr/bin/env python print("this will raise a division by zero exception") print(2/0) It More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python: Traceback (most recent call last): /NameError: name 'me' is not defined
bpy.context.edit_object is only defined while in Edit mode on something, and the data could be of any type anyway. Use bpy.context.active_object instead, and you should check that me.type == 'MESH' first. More on reddit.com
๐ŸŒ r/blenderhelp
4
1
August 9, 2022
Python Traceback error, unable to import/export anything.
Have a look at this thread... https://developer.blender.org/T99440 It's either malware on your system or an out of date/dodgy add-on has corrupted things. There are fixes for both listed. More on reddit.com
๐ŸŒ r/blender
2
3
July 18, 2022
Just downloaded python 3.10 and no matter what I type I keep getting this error
When you see >>> you're already in the Python interpreter, so the commands you enter have to be statements in the Python programming language. More on reddit.com
๐ŸŒ r/learnpython
48
98
April 25, 2022
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ traceback-in-python
Traceback in Python - GeeksforGeeks
August 1, 2020 - format_exception_only() : Formats the exception part of the traceback. It also returns strings ending newlines. Normally, the generator emits a single string; however, for SyntaxError exceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the output. Example : Python3 ยท # importing the modules import traceback import sys a=3 b=0 try: a/b except Exception as e: exc_type, exc_value, exc_tb = sys.exc_info() tb = traceback.TracebackException(exc_type, exc_value, exc_tb) print(''.join(tb.format_exception_only())) Output : ZeroDivisonError: division by zero StackSummary Class : The objects of this class represent a call stack ready for formatting.
๐ŸŒ
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 ...
๐ŸŒ
Real Python
realpython.com โ€บ python-traceback
Understanding the Python Traceback โ€“ Real Python
July 29, 2019 - The Python documentation defines when this exception is raised: Raised when the import statement has troubles trying to load a module. Also raised when the โ€˜from listโ€™ in from ... import has a name that cannot be found.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_module_traceback.asp
Python traceback Module
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... import traceback try: result = 10 / 0 except ZeroDivisionError: tb = traceback.format_exc() print('Exception caught and formatted') Try it Yourself ยป
๐ŸŒ
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_
Find elsewhere
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ python โ€บ print stack traces in python
Print stack traces in Python | Sentry
July 3, 2026 - The optional limit parameter allows us to control how many entries are printed โ€” by default, the entire stack trace will be printed. Consider the following example script: import traceback def trace(): traceback.print_stack() def do_something(): ...
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ traceback-with-variables
traceback-with-variables 2.2.1
JavaScript is disabled in your browser. Please enable JavaScript to proceed ยท A required part of this site couldnโ€™t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-print-exception-stack-trace-in-python
How to Print Exception Stack Trace in Python - GeeksforGeeks
April 7, 2025 - Instead of printing directly, it allows further processing, such as storing errors in logs or sending them in reports. This method provides flexibility while maintaining detailed traceback information. ... import traceback try: 1 / 0 # division by zero except Exception: error_msg = traceback.format_exc() print(error_msg)
๐ŸŒ
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 - Clears the local variables of all the stack frames in a traceback tb by calling the clear() method of each frame object. New in version 3.4. 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 = input(">>> ") try: exec(source, envdir) except Exception: print("Exception in user code:") print("-"*60) traceback.print_exc(file=sys.stdout) print("-"*60) envdir = {} while True: run_user_code(envdir)
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ python-traceback
Python Traceback: How to Read? & Error Types? (with Example)
April 12, 2023 - The Python traceback module is ... for using Tracebacks. Moreover, once an individual has imported the traceback module, it can be used to manipulate tracebacks, edit or print it too....
๐ŸŒ
Readthedocs
ironpython-test.readthedocs.io โ€บ en โ€บ latest โ€บ library โ€บ traceback.html
27.10. traceback โ€” Print or retrieve a stack traceback โ€” IronPython 2.7.2b1 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)
๐ŸŒ
O'Reilly
oreilly.com โ€บ library โ€บ view โ€บ python-standard-library โ€บ 0596000960 โ€บ ch02s11.html
The traceback Module - Python Standard Library [Book]
May 10, 2001 - File: traceback-example-1.py # note! importing the traceback module messes up the # exception state, so you better do that here and not # in the exception handler import traceback try: raise SyntaxError, "example" except: traceback.print_exc() Traceback (innermost last): File "traceback-example-1.py", line 7, in ?
Author: Fredrik Lundh
Published: 2001
Pages: 304
๐ŸŒ
CodeRivers
coderivers.org โ€บ blog โ€บ traceback-in-python
Demystifying Traceback in Python - CodeRivers
February 22, 2026 - When working in an interactive Python session (e.g., the Python shell or Jupyter Notebook), tracebacks can be used to quickly identify and fix errors. For example, if we make a mistake in a function definition: def multiply_numbers(a, b): return a * c # Typo: should be 'b' instead of 'c' try: result = multiply_numbers(5, 3) except NameError as e: import traceback traceback.print_exc()
๐ŸŒ
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)
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 3 โ€บ traceback โ€บ index.html
traceback โ€” Exceptions and Stack Traces
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 as 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: $ python3 traceback_print_exc.py print_exc() with no exception: NoneType: None print_exc(): Traceback (most recent call las