Last Updated: February 25, 2016
· ericmarcos

Start pdb only when an Exception is raised

You know, debugging in Python can get tricky when you use many libraries or have a large codebase. Sometimes I don't even know where to put pdb.set_trace() and it takes a while to figure out what exact line caused the problem.

To start pdb only when the exception is raised (and not caught), put this module in your python path:

import sys

def info(type, value, tb):
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # we are in interactive mode or we don't have a tty-like
        # device, so we call the default hook
        sys.__excepthook__(type, value, tb)
        import traceback, pdb
        # we are NOT in interactive mode, print the exception...
        traceback.print_exception(type, value, tb)
        # ...then start the debugger in post-mortem mode.

sys.excepthook = info

and add this line in your main module:

import debug

Thanks to the 2nd answer in this StackOverflow question:

2 Responses
Add your response

You forgot the bottom: sys.excepthook = info

over 1 year ago ·

Just edited it, thank you!

over 1 year ago ·