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
Given a list of tuples or FrameSummary objects as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. 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, ]*, show_group=False)¶
🌐
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 ...
🌐
EyeHunts
tutorial.eyehunts.com › home › python exception stack trace to string
Python exception stack trace to string - Tutorial - By EyeHunts
February 3, 2023 - Use traceback.format_exc() to exception stack trace to string in Python. it can handle exceptions caught anywhere.
🌐
Cwestblog
cwestblog.com › 2021 › 11 › 15 › python-snippet-get-exception-stack-trace
Python Snippet – Get Exception Stack Trace – Chris West's Blog
November 15, 2021 - Every once in a while I just need to get the stack trace of an exception as a string so that I can log the error in a separate system. Here is a quick way to do that: ... Blog (346) CSharp (1) Games (3) HTA (2) Java (5) JavaScript (220) JScript (149) Math (49) Microsoft Office (16) Movie Trailers (2) PHP (13) POW Answer (2) Problem of the Week (31) Python ...
🌐
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 ...
🌐
Stefaan Lippens
stefaanlippens.net › python-traceback-in-catch
Get stacktrace in Python catch body - Stefaan Lippens inserts content here
February 14, 2013 - So you have some Python code in a try-catch, and you want the typical Python stacktrace (aka traceback, aka backtrace) in a way you can manipulate? ... import traceback import logging try: stuff() except Exception: # Just print traceback print "something went wrong, here is some info:" traceback.print_exc() # Get traceback as a string and do something with it error = traceback.format_exc() print error.upper() # Log it through logging channel logging.error('Ooops', exc_info=True)
🌐
Embedded Inventor
embeddedinventor.com › home › python exception to string
Python Exception to string
September 27, 2023 - Stack-trace in Python is packed into an object named traceback object. This is an interesting one as the traceback class in Python comes with several useful methods to exercise complete control over what is printed. Let us see how to use these options using some examples! import traceback try: my_list = [1,2] print (my_list[3]) except Exception: traceback.print_exc()
🌐
Python Module of the Week
pymotw.com › 2 › traceback
traceback – Extract, format, and print exceptions and stack traces. - Python Module of the Week
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.
Find elsewhere
🌐
Bacancy Technology
bacancytechnology.com › qanda › python › python-try-except-print-error
How to print as exception in Python
July 31, 2023 - For example, if the exception is a KeyError, the output will be the key that was not found. If you want to print more detailed information about an exception, you can use the traceback module. The traceback module provides a number of functions that can be used to print the stack trace of an 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, ...
🌐
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
🌐
Sentry
sentry.io › sentry answers › python › print stack traces in python
Print stack traces in Python | Sentry
July 3, 2026 - If we just want the stack trace on its own, we will need to take a more manual approach, using Python’s built-in inspect module to iterate through each frame of the exception’s traceback object. For example: import inspect def print_stacktrace(exception): stacktrace = exception.__traceback__ for frame in inspect.getinnerframes(stacktrace): filename = frame.filename lineno = frame.lineno function = frame.function code_context = frame.code_context code_context = code_context[0].strip() if code_context else "No code context" print(f"File \"{filename}\", line {lineno}, in {function}") print(f" {code_context}")
🌐
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.
🌐
The Blog at Ayyjohn
ayyjohn.com › posts › anatomy-of-a-python-stack-trace
How to Read Python Stack Traces | The Blog at Ayyjohn
November 14, 2021 - Traceback (most recent call last): File "ayyjohn.github.io/code_examples/python/stack_traces.py", line 10, in <module> print(get_username(user)) File "ayyjohn.github.io/code_examples/python/stack_traces.py", line 2, in get_username return user['useranme'] KeyError: 'useranme' Bummer, but simple enough. First, the actual anatomy. A stack trace starts with the actual Exception thrown in Python.
🌐
One Two Bytes
onetwobytes.com › 2021 › 11 › 12 › print-stack-trace-python-exception
Printing Stack Traces in Python Exceptions: A Comprehensive Guide | One Two Bytes
February 6, 2024 - Encountering errors in Python is inevitable. But with stack traces, you can pinpoint the exact location of an exception and diagnose issues effectively. Here’s a step-by-step guide: ... try: processEvent() # Call the function that might raise an exception except Exception as e: print("Error encountered:", e) traceback.print_exc() # Print the detailed stack trace
🌐
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 - format_exception() - This method works exactly the same as print_exception() method with the only difference that it returns a list of strings where each string is a single trace of the stack.
🌐
Real Python
realpython.com › python-traceback
Understanding the Python Traceback – Real Python
July 29, 2019 - Tracebacks are known by many names, including stack trace, stack traceback, backtrace, and maybe others. In Python, the term used is traceback. When your program results in an exception, Python will print the current traceback to help you know what went wrong. Below is an example to illustrate this situation: ... Here, greet() gets called with the parameter someone. However, in greet(), that variable name is not used. Instead, it has been misspelled as ...