How to print exception traceback in Python

Aug 31, 2020 · Updated: Jan 30, 2021 · by Tim Kamanin

Sometimes you're deep down in the code, and you need to debug an error quickly, send a traceback somewhere or log it into a file.

Here's how you can print the traceback of an error in Python:

import traceback

    raise Boom('This is where our code blows')
except Exception:
    # here's how you get a traceback output
    traceback_output = traceback.format_exc()
    # Now you can print it, or send it, or save it in a file

It's a quick and dirty solution, and you probably should be using more sophisticated ways of debugging like error logging, but there are situations when you don't have much of a choice.

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓