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
🌐
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, ]*, ...
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!
🌐
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. The Python documentation defines when this exception is raised:
🌐
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. This error message is then stored in error_msg and printed, providing detailed debugging information about ...
🌐
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_
🌐
Embedded Inventor
embeddedinventor.com › home › python exception to string
Python Exception to string
September 27, 2023 - Traceback (most recent call last): File "<ipython-input-38-f9a1ee2cf77a>", line 5, in <module> print (my_list[3]) IndexError: list index out of range · which contains the entire error messages printed by the Python interpreter if we fail to handle the exception. Here, instead of crashing the program, we have printed this entire message using our exception handler with the help of the print_exc() method of the traceback class.
🌐
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().
🌐
Narkive
comp.lang.python.narkive.com › eIjyWKhW › traceback-as-string
traceback as string
Permalink I haven't been using this function for very long, but it seems to work. You pass it the exception object, and it returns a string. =================================================== def exception_format(e): """Convert an exception object into a string, complete with stack trace info, ...
Find elsewhere
🌐
Ntua
ftp.ntua.gr › mirror › python › doc › 1.6 › lib › module-traceback.html
3.7 traceback -- Print or retrieve a stack traceback
The optional limit and file arguments ... print_exception(). ... 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 ...
🌐
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 - Python provides a traceback when an exception is raised. You can extract, format, and print stack traces with the Python traceback module.
🌐
Real Python
realpython.com › ref › stdlib › traceback
traceback | Python Standard Library – Real Python
Colorizes traceback output by default in Python 3.13 and later, configurable through the PYTHON_COLORS and NO_COLOR environment variables · Captures complete exception information for debugging and logging ... >>> import traceback >>> try: ... int("abc") ... except ValueError: ... print(traceback.format_exc()) Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: 'abc'
🌐
Python
docs.python.org › 3.1 › library › traceback.html
27.8. traceback — Print or retrieve a stack traceback — Python v3.1.5 documentation
The optional limit and file arguments ... print_exception(). ... 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 ...
🌐
Readthedocs
boltons.readthedocs.io › en › latest › tbutils.html
tbutils - Tracebacks and call stacks — boltons 25.0.0 documentation
Create an ExceptionInfo object from the exception’s type, value, and traceback, as returned by sys.exc_info(). See also from_current(). ... Returns a string formatted in the traditional Python built-in style observable when an exception is not caught.
Top answer
1 of 7
137

The answer to this question depends on the version of Python you're using.

In Python 3

It's simple: exceptions come equipped with a __traceback__ attribute that contains the traceback. This attribute is also writable, and can be conveniently set using the with_traceback method of exceptions:

raise Exception("foo occurred").with_traceback(tracebackobj)

These features are minimally described as part of the raise documentation.

All credit for this part of the answer should go to Vyctor, who first posted this information. I'm including it here only because this answer is stuck at the top, and Python 3 is becoming more common.

In Python 2

It's annoyingly complex. The trouble with tracebacks is that they have references to stack frames, and stack frames have references to the tracebacks that have references to stack frames that have references to... you get the idea. This causes problems for the garbage collector. (Thanks to ecatmur for first pointing this out.)

The nice way of solving this would be to surgically break the cycle after leaving the except clause, which is what Python 3 does. The Python 2 solution is much uglier: you are provided with an ad-hoc function,sys.exc_info(), which only works inside the except clause. It returns a tuple containing the exception, the exception type, and the traceback for whatever exception is currently being handled.

So if you are inside the except clause, you can use the output of sys.exc_info() along with the traceback module to do various useful things:

>>> import sys, traceback
>>> def raise_exception():
...     try:
...         raise Exception
...     except Exception:
...         ex_type, ex, tb = sys.exc_info()
...         traceback.print_tb(tb)
...     finally:
...         del tb
... 
>>> raise_exception()
  File "<stdin>", line 3, in raise_exception

But as your edit indicates, you're trying to get the traceback that would have been printed if your exception had not been handled, after it has already been handled. That's a much harder question. Unfortunately, sys.exc_info returns (None, None, None) when no exception is being handled. Other related sys attributes don't help either. sys.exc_traceback is deprecated and undefined when no exception is being handled; sys.last_traceback seems perfect, but it appears only to be defined during interactive sessions.

If you can control how the exception is raised, you might be able to use inspect and a custom exception to store some of the information. But I'm not entirely sure how that would work.

To tell the truth, catching and returning an exception is kind of an unusual thing to do. This might be a sign that you need to refactor anyway.

2 of 7
116

Since Python 3.0[PEP 3109] the built in class Exception has a __traceback__ attribute which contains a traceback object (with Python 3.2.3):

>>> try:
...     raise Exception()
... except Exception as e:
...     tb = e.__traceback__
...
>>> tb
<traceback object at 0x00000000022A9208>

The problem is that after Googling __traceback__ for a while I found only few articles but none of them describes whether or why you should (not) use __traceback__.

However, the Python 3 documentation for raise says that:

A traceback object is normally created automatically when an exception is raised and attached to it as the __traceback__ attribute, which is writable.

So I assume it's meant to be used.

🌐
Coderz Column
coderzcolumn.com › tutorials › python › traceback-how-to-extract-format-and-print-error-stack-traces-in-python
traceback - How to Extract, Format, and Print Error Stack Traces in Python by Sunny Solanki
January 14, 2021 - In this example, we have called method named exc_info() of sys module that returns tuple (exception type, exception value, exception traceback). This tuple has information about a recent exception that was caught by try-except block. We have then given this tuple to print_exception() method to print an error stack trace. We have directed stack trace to standard output in all of our examples. Please make a note that when we used print_exception() method, it printed information about exceptions as well which was not getting printed with print_tb() method.
🌐
Jython
jython.org › jython-old-sites › docs › library › traceback.html
26.7. traceback — Print or retrieve a stack traceback — Jython v2.5.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])
🌐
Python Module of the Week
pymotw.com › 3 › traceback › index.html
traceback — Exceptions and Stack Traces
The traceback module works with the call stack to produce error messages. A traceback is a stack trace from the point of an exception handler down the call chain to the point where the exception was raised.