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 scratch.py 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 scratch.py --drop-into-debugger
> /home/matt/scratch.py(15)main()
-> 1/0
(Pdb)

When I don’t add the --drop-into-debugger option, then of course the uncaught exception just crashes the script:
$ python scratch.py
Traceback (most recent call last):
File "scratch.py", line 23, in
main()
File "scratch.py", line 15, in main
1/0
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

@decorator
def into_debugger(f, *args, **kwargs):
try:
return f(*args, **kwargs)
except:
pdb.post_mortem()

def main():
x = 99
1/0

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

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.