Add an option for your script to drop into the debugger

I like using the python debugger to, umm, debug stuff. Just recently I wanted to use pdb to poke around in a script that would intermittently crash. I wanted to add an option to my script that would drop me into pdb when the script dies.

This turned out to be trivial to write. The script doesn’t do much, but if you add the --drop-into-debugger option, you’ll get dumped into a pdb session, where you can study the problem more closely, like this:$ python --drop-into-debugger
> /home/matt/
-> 1/0

When I don’t add the --drop-into-debugger option, then of course the uncaught exception just crashes the script:
$ python
Traceback (most recent call last):
File "", line 23, in
File "", line 15, in main
ZeroDivisionError: integer division or modulo by zero

The code involved was really easy to write. I wrote a decorator called into_decorator with the decorator module, but that’s not strictly necessary. Here’s the code:

# vim: set expandtab ts=4 sw=4 filetype=python:

import pdb, sys
from decorator import decorator

def into_debugger(f, *args, **kwargs):
return f(*args, **kwargs)

def main():
x = 99

if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == '--drop-into-debugger':

That pdb.post_mortem function does the interesting work of inspecting the most recently caught exception. The pdb documentation is pretty dang sparse, but in this case, I got what I needed.

Anyhow, I hope this helps somebody out. I’ll probably be adding a –drop-into-debugger option on every script I write from now on.

5 thoughts on “Add an option for your script to drop into the debugger

  1. you might want to name it '–pdb' for uniformity, is used by some testing tools to bail into debugging on failing tests.

Comments are closed.