Debugging Python scripts on Exceptions

If you use nose for running your unit tests in Python, it has this extremely handy feature. If you pass it --pdb or --pdb-failures, it will invoke the Python debugger when your tests raise exceptions or their asserts fail.

I really like this behavior, since it makes fixing the code significantly easier. I liked it so much, I reimplemented it for my CLI scripts.

try:
    main()
except Exception, e:
    if not opts.debug:
        raise

    import sys
    import traceback
    import pdb
    info = sys.exc_info()
    traceback.print_exception(*info)

    pdb.post_mortem(info[2])

If you use optparse, it’s trivial to add a --debug option which enables the behavior. Interestingly enough, when I run the script in an shell under Emacs, it notices when it enters PDB and fires up the usual GUD source tracking mode.

2009/09/24
Previously On Atomized:

Discussion

[...] I like the with statement so much, I reimplemented my previous post as a reusable context [...]

⚛ Encapsulated debugging on Python exceptions
2009/09/24

Participate