Let's say there's some exception you're encountering in Python code. Often times you'll put some of your statements into try / except blocks to catch the error. Sometimes you might want to log this exception or insert it into a database for some later analysis.

If you insert the exception into a database it might be helpful if you structure the stack trace (i.e. traceback) as a list of strings. I'll quickly show you how to format the stack trace of this exception (its traceback) so that it's a list of strings.

For example assuming this is your Python code:

try:
    raise Exception('Something went wrong')
except:
    # I've now caught the exception, but I want to structure the stack trace
    # as a list of strings and insert this into a database

To get the stack trace of this exception as a list of strings you'll need to use the sys and traceback modules which are a part of the Python standard library. sys is used to get the exception. traceback is used to output the traceback as a list of strings (the traceback contains the stack trace).

First call sys.exc_info to get the exception information. sys.exc_info() returns a 3-tuple of (type, value, traceback) which is information for the most recently encountered exception. It's not important to know what the values in the 3-tuple are, just know that these values are required as parameters to many of the traceback functions. You invoke traceback.format_exception with these three values. This function will output the exception's traceback as a list of formatted strings. So, traceback.format_exception(type, value, traceback), with type, value, and traceback coming from sys.exc_info().

So, using the above example, your code would now look like:

import sys
import traceback
import pprint # to pretty print the stack trace

stack_trace = []
try:
    raise Exception("Something went wrong")
except:
    stack_trace = traceback.format_exception(*sys.exc_info())

print("Here's the stack trace as a list of strings:")
pprint.pprint(stack_trace)

Running this code outputs:

Here's the stack trace as a list of strings:
['Traceback (most recent call last):\n',
 '  File "your-script.py", line 7, in <module>\n'
 '    raise Exception("Something went wrong")\n',
 'Exception: Something went wrong\n']