Mar 20, 2013 python

Python debugger notes.

pdb

Add in code to create break

import pdb; pdb.set_trace()

Commands

s: step
n: next
unt : until
r: return
c: continue, stop only at breakpoint
j <lineno>: jump
p <exp> : print evaluated expression
pp <exp> : pretty-print 
q: quit

pdb++

sim to ipdb, but less buggy?

pudb

recommended, uses terminal based GUI.

import pudb; pudb.set_trace()

To run from beginning

pudb myscript.py

Commands

? : help
C-p: change appearance
!
c: continue
n: next
j/k: up/down
b: set breakpoint

ipdb

Install

pip install ipdb

Set breakpoint

import ipdb; ipdb.set_trace()

Commands

s: step into
n: step over
c: continue to next breakpoint
?: help
? n: more help on 'n'
l: more context

Editor-based

Misc

Tip from HN reader

There’s a nice trick to enable this behavior for standard Python code run at the command line. Write the body of your code inside a main() function, then call it using the following toplevel block:

     if __name__ == "__main__":
         try:
             main()
         except KeyboardInterrupt: # allow ctrl-C
             raise
         except Exception as e:
             import sys, traceback, pdb
             print e
             type, value, tb = sys.exc_info()
             traceback.print_exc()
             pdb.post_mortem(tb) This will catch any exceptions and throw you into PDB in the context where the exception was raised. You probably don't want to leave it in production code, but it's super useful for development.

Debugging messages/logging

Debugging messages, use “warning”

import warnings
...
warnings.warn("Some warning",DeprecationWarning)