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
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, ]*, ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-print-exception-stack-trace-in-python
How to Print Exception Stack Trace in Python - GeeksforGeeks
July 15, 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 - Traceback (most recent call last): ... a raised exception goes unhandled. But you can also obtain it as a string by calling traceback.format_exc()....
🌐
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.
🌐
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
In this blog, we’ll explore how to use sys.exc_info()[2] to access the traceback object and the traceback module to convert it into a string. We’ll cover practical examples, best practices, and common pitfalls to help you master traceback ...
🌐
GeeksforGeeks
geeksforgeeks.org › traceback-in-python
Traceback in Python - GeeksforGeeks
August 1, 2020 - It returns a list of strings each ending in a new line. traceback.format_exception(etype, value, tb, limit = None, chain = True) : Formats stack trace and exception information. The arguments have the same meaning as the corresponding arguments to print_exception().
🌐
Python Module of the Week
pymotw.com › 2 › traceback
traceback – Extract, format, and print exceptions and stack traces. - Python Module of the Week
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. 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.
🌐
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 ...
Find elsewhere
🌐
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 “traceback.format_exc()” function retrieves a string that contains the stack trace of the exception. ... This outcome indicates that the exception has been successfully converted into a string. In Python, the “repr()” function is used to return a printable representation of an object ...
🌐
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 to an integer or calling len() on an object where its length isn’t defined.
🌐
Python
docs.python.org › 3.1 › library › traceback.html
27.8. traceback — Print or retrieve a stack traceback — Python v3.1.5 documentation
Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list. traceback.format_exception(type, value, tb, limit=None, chain=True)¶
🌐
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
Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list. traceback.format_exception(type, value, tb, limit=None, chain=True)¶
🌐
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.
🌐
Ntua
ftp.ntua.gr › mirror › python › doc › 1.6 › lib › module-traceback.html
3.7 traceback -- Print or retrieve a stack traceback
Return a list of up to limit ``pre-processed'' stack trace entries extracted from the traceback object traceback. It is useful for alternate formatting of stack traces. If limit is omitted or None, all entries are extracted. 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.
🌐
Acid & Base
sceweb.sce.uhcl.edu › helm › WEBPAGE-Python › documentation › python_tutorial › lib › module-traceback.html
3.6 traceback -- Print or retrieve a stack traceback.
Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None. ... Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value.
🌐
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