Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nepsilon/107971fb4b65c9cea7c58cbdcea2abb6 to your computer and use it in GitHub Desktop.
Save nepsilon/107971fb4b65c9cea7c58cbdcea2abb6 to your computer and use it in GitHub Desktop.
Python: How to print the full traceback without exiting the program? — First published in fullweb.io issue #81

Python: How to print the full traceback without exiting the program?

The exception handling block except Exception as ex: print(ex) will only print the exception message and not its traceback.

That’s good to know, but we need more info than this to debug properly. Namely the line that raised the exception, together with its stack trace.

The traceback module, part of the stdlib, will help us with this:

import traceback

try:
    raise Exception(“nop”)
except Exception as ex:
    traceback.print_exc()

# Output:
Traceback (most recent call last):
  File<stdin>”, line 2, in <module>
Exception: nop

The traceback module also works well with Python 2.x.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment