Last Updated: February 25, 2016
·
7.009K
· 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:

debug.py

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)
    else:
        import traceback, pdb
        # we are NOT in interactive mode, print the exception...
        traceback.print_exception(type, value, tb)
        print
        # ...then start the debugger in post-mortem mode.
        pdb.post_mortem(tb)

sys.excepthook = info

and add this line in your main module:

import debug

Thanks to the 2nd answer in this StackOverflow question:
http://stackoverflow.com/questions/242485/starting-python-debugger-automatically-on-error

2 Responses
Add your response

You forgot the bottom: sys.excepthook = info

over 1 year ago ·

True!
Just edited it, thank you!

over 1 year ago ·