See the traceback module, specifically the format_exc() function. Here.

import traceback

try:
    raise ValueError
except ValueError:
    tb = traceback.format_exc()
else:
    tb = "No error"
finally:
    print(tb)
Answer from kindall on Stack Overflow
Top answer
1 of 12
914

See the traceback module, specifically the format_exc() function. Here.

import traceback

try:
    raise ValueError
except ValueError:
    tb = traceback.format_exc()
else:
    tb = "No error"
finally:
    print(tb)
2 of 12
130

Let's create a decently complicated stacktrace, in order to demonstrate that we get the full stacktrace:

def raise_error():
    raise RuntimeError('something bad happened!')

def do_something_that_might_error():
    raise_error()

Logging the full stacktrace

A best practice is to have a logger set up for your module. It will know the name of the module and be able to change levels (among other attributes, such as handlers)

import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

And we can use this logger to get the error:

try:
    do_something_that_might_error()
except Exception as error:
    logger.exception(error)

Which logs:

ERROR:__main__:something bad happened!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

And so we get the same output as when we have an error:

>>> do_something_that_might_error()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

Getting just the string

If you really just want the string, use the traceback.format_exc function instead, demonstrating logging the string here:

import traceback
try:
    do_something_that_might_error()
except Exception as error:
    just_the_string = traceback.format_exc()
    logger.debug(just_the_string)

Which logs:

DEBUG:__main__:Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
🌐
Python
docs.python.org › 3 › library › traceback.html
traceback — Print or retrieve a stack traceback
Format the exception part of a traceback using an exception value such as given by sys.last_exc. The return value is a list of strings, each ending in a newline.
🌐
Alexwlchan
alexwlchan.net › notes › 2025 › get-python-traceback-as-string
Get a string representation of a Python traceback with traceback.format_exc() – alexwlchan
June 13, 2025 - $ python3 exception.py 'Traceback (most recent call last):\n File "exception.py", line 4, in <module>\n 1/0\n ~^~\nZeroDivisionError: division by zero\n' It’s all the text that would be printed to stderr, but now saved in a handy string I can keep for later.
🌐
Narkive
comp.lang.python.narkive.com › eIjyWKhW › traceback-as-string
traceback as string
=================================================== def exception_format(e): """Convert an exception object into a string, complete with stack trace info, suitable for display. """ import traceback info = "".join(traceback.format_tb(sys.exc_info()[2])) return str(e) + "\n\n" + info ==================================================== Here's an example of how to use it.
🌐
Linux Hint
linuxhint.com › convert-an-exception-to-a-string-in-python
How Do I Convert an Exception to a String in Python – Linux Hint
The “except” block assigns ... has been converted into a string appropriately. The “traceback.format_exc()” function of the “traceback” module can also be used to convert an exception to a string....
🌐
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 functions for extracting raw tracebacks from the current runtime environment (either an exception handler for a traceback, or the regular stack). The extracted stack trace is a sequence of tuples containing the filename, line number, function name, and text of the source line. Once extracted, the stack trace can be formatted using functions like format_exception(), format_stack(), etc. The format functions return a list of strings with messages formatted to be printed. There are shorthand functions for printing the formatted values, as well.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-print-exception-stack-trace-in-python
How to Print Exception Stack Trace in Python - GeeksforGeeks
April 7, 2025 - Explanation: The except block catches the exception and uses traceback.format_exc() to capture the complete error traceback as a string.
🌐
DEV Community
dev.to › vincenttommi › getting-the-traceback-as-a-string-in-python-333g
Getting the Traceback as a String in python - DEV Community
October 19, 2023 - But you can also obtain it as a string by calling traceback.format_exc(). This function is useful if you want the information from an exception’s traceback but also want an except statement to gracefully handle the exception.
Find elsewhere
🌐
pythontutorials
pythontutorials.net › blog › how-can-i-get-the-traceback-object-sys-exc-info-2-same-as-sys-exc-traceback-as-a-string
How to Get the Traceback Object as a String in Python: Using sys.exc_info()[2] and traceback Module
However, this object is not human-readable on its own. To convert it into a string, we need the traceback module. The traceback module is Python’s built-in tool for processing traceback objects.
🌐
Real Python
realpython.com › python-traceback
Understanding the Python Traceback – Real Python
July 29, 2019 - Also, with SyntaxError tracebacks, the regular first line Traceback (most recent call last): is missing. That is because the SyntaxError is raised when Python attempts to parse your code, and the lines aren’t actually being executed. ... The TypeError is raised when your code attempts to do something with an object that can’t do that thing, such as trying to add a string ...
🌐
GeeksforGeeks
geeksforgeeks.org › traceback-in-python
Traceback in Python - GeeksforGeeks
August 1, 2020 - The arguments have the same meaning as the corresponding arguments to print_exception(). It returns a list of strings each ending in new line and some have internal newlines too. When these lines are concatenated and printed they generate an ...
🌐
Embedded Inventor
embeddedinventor.com › home › python exception to string
Python Exception to string
September 27, 2023 - Here we have used the format_exc() method available in the traceback class to get the traceback information as a string and used splitlines() method to transform the string into a list of lines and stored that in a list object named traceback_lines
🌐
EyeHunts
tutorial.eyehunts.com › home › python exception stack trace to string
Python exception stack trace to string - Tutorial - By EyeHunts
February 3, 2023 - Answer: It’s traceback.extract_stack() if you want convenient access to module and function names and line numbers, or ''.join(traceback.format_stack()) if you just want a string that looks like the traceback.print_stack() output. Do comment if you have any doubts or suggestions on this Python stack trace topic.
🌐
Readthedocs
boltons.readthedocs.io › en › latest › tbutils.html
tbutils - Tracebacks and call stacks — boltons 25.0.0 documentation
Render the Callpoint as it would appear in a standard printed Python traceback. Returns a string with filename, line number, function name, and the actual code line of the error on up to two lines.
🌐
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 - Here’s an example of a Python traceback in response to an AttributeError: Starting from the bottom, we can see that we've generated an AttributeError in line 2 of our code. This was caused by trying to use the attribute append on the variable drinks, which we defines as a string.
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
docs.python.org › 3.0 › library › traceback.html
traceback — Print or retrieve a stack traceback — Python v3.0.1 documentation
A “pre-processed” stack trace entry is a quadruple (filename, line number, function name, text) representing the information that is usually printed for a stack trace. The text is a string with leading and trailing whitespace stripped; if the source is not available it is None.