Sunday 17 August 2014

IPython debugging

Debugger commands

  • h (help) Display command list
  • help command Show documentation for command
  • c (continue) Resume program execution
  • q (quit) Exit debugger without executing any more code
  • b (break) number Set breakpoint at number in current file
  • b path/to/file.py:number Set breakpoint at line number in specified file
  • s (step) Step into function call
  • n (next) Execute current line and advance to next line at current level
  • u/d (up) / (down) Move up/down in function call stack
  • a (args) Show arguments for current function
  • debug statement Invoke statement statement in new (recursive) debugger
  • l (list) statement Show current position and context at current level of stack
  • w (where) Print full stack trace with context at current position

Post-mortem debugging

%debug

Entering %debug immediately after an exception has occurred drops you into the stack frame where the exception was raised

Utility functions

Poor man’s breakpoint

def set_trace():
    from IPython.core.debugger import Pdb
    Pdb(color_scheme='Linux').set_trace(sys._getframe().f_back)

Putting set_trace() in your code will automatically drop into the debugger when the line is executed.

Interactive function debugging

def debug(f, *args, **kwargs):
    from IPython.core.debugger import Pdb
    pdb = Pdb(color_scheme='Linux')
    return pdb.runcall(f, *args, **kwargs)

Passing a function to debug will drop you into the debugger for an arbitrary function call.

debug(fn, arg1, arg2, arg3, kwarg=foo, kwarg=bar)

Interactive script debugging

Executing a script via %run with -d will start the script in the debugger

%run -d ./my_script.py

Specifying a line number with -b starts the script with a breakpoint already set

%run -d -b20 ./my_script.py # sets a breakpoint on line 20

Taken from Python for Data Anlysis by Wes McKinney

No comments:

Post a Comment