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

  • Uses ipython, requires ipython
  • recommended, but might be buggy.

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

  • Pycharm debugger: highly recommended
  • Pydev: also highly recommended, uses Eclipse, it is also used by Pycharm
  • ptvs (Visual Studio)

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)