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)
🌐
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.
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
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!")
🌐
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_
🌐
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. (Source) Here’s an example of the ImportError and ModuleNotFoundError being raised: ... >>> import asdf Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'asdf' >>> from collections import asdf Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name 'asdf'
🌐
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 »
Find elsewhere
🌐
Chennai Mathematical Institute
cmi.ac.in › ~madhavan › courses › prog2-2015 › docs › python-3.4.2-docs-html › library › traceback.html
29.9. traceback — Print or retrieve a stack traceback — Python 3.4.2 documentation
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)
🌐
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
🌐
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(): ...
🌐
7-Zip Documentation
documentation.help › Python-3.3 › traceback.html
28.9. traceback — Print or retrieve a stack traceback - Python 3.3 Documentation
>>> import traceback >>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'), ... ('eggs.py', 42, 'eggs', 'return "bacon"')]) [' File "spam.py", line 3, in <module>\n spam.eggs()\n', ' File "eggs.py", line 42, in eggs\n return "bacon"\n'] >>> an_error = IndexError('tuple index out of range') >>> traceback.format_exception_only(type(an_error), an_error) ['IndexError: tuple index out of range\n'] ... © Copyright 1990-2013, Python Software Foundation.
🌐
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
🌐
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('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
🌐
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 Pool
pythonpool.com › home › blog › cracking the python traceback secret
Cracking The Python Traceback Secret - Python Pool
November 26, 2021 - Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many values to unpack (expected 3) ... Although the system raises the error when something is wrong with our code, we can also print the exception on our console. It works the same way as to try and except block with the block of code to print the exception or error that occurred. Let’s see this. import traceback # importing traceback module x = 5 try: y = x.upper() except: traceback.print_exc() # printing stack trace print("end of the program") # Line of code to demonstrate that all the above lines of code executed
🌐
CodeRivers
coderivers.org › blog › traceback-python
Unraveling the Mysteries of Python Traceback - CodeRivers
April 7, 2025 - The traceback shows the path of ... way back up the call stack. The simplest way to use the traceback module is to print the traceback information. This can be done using the print_exc() function. Here's an example: import traceback try: result = 1 / 0 except ZeroDivisionError: ...
🌐
FavTutor
favtutor.com › blogs › python-traceback
Python Traceback: How to Read? & Error Types? (with Example)
April 12, 2023 - The Python traceback module is an in-built module that offers capabilities and provides functionalities for using Tracebacks. Moreover, once an individual has imported the traceback module, it can be used to manipulate tracebacks, edit or print it too.