Python debugger

Sometime is useful to be able to understand what is going on inside a function or a class. Python in the standar library has a package pdb, that integrate python with a debugger.

Ipython notebook at the moment is not able to manage pdb from the browser, so you should use caling your program from a shell.

Note: Spyder integrate a python debugger in the GUI.

You can execute line by line a python file with:

In [ ]:
python -m ipdb mymodule.py
In [ ]:
ipdb mymodule.py

Or you can call ipdb at certain point of your code adding the line

In [ ]:
import ipdb; ipdb.set_trace()

Other common functions are:

In [ ]:
import ipdb
ipdb.set_trace()
ipdb.pm()
ipdb.run('x[0] = 3')
result = ipdb.runcall(function, arg0, arg1, kwarg='foo')
result = ipdb.runeval('f(1, 2) - 3')

Or you can said to open a ipdb shell when an exception is raised, with:

In [ ]:
from ipdb import launch_ipdb_on_exception

with launch_ipdb_on_exception():
    [...]

Once that you are inside a ipdb shell you have several commands that you can run, type h for the help:

ipdb> h Documented commands (type help ): ======================================== EOF cl disable interact pdef q s until a clear display j pdoc quit source up alias commands down jump pfile r step w args condition enable ll pinfo restart tbreak whatis b cont exit longlist pinfo2 return u where break continue h n pp retval unalias bt d help next print run undisplay c debug ignore p psource rv unt Miscellaneous help topics: ========================== pdb exec Undocumented commands: ====================== l list
  • h(elp)
  • w(here): Print a stack trace, with the most recent frame at the bottom. An arrow indicates the current frame, which determines the context of most commands.
  • d(own): Move the current frame one level down in the stack trace (to a newer frame).
  • u(p): Move the current frame one level up in the stack trace (to an older frame).
  • b(reak) [[filename:]lineno | function[, condition]]
  • s(tep) Execute the current line, stop at the first possible occasion
  • n(ext) Continue execution until the next line in the current function
  • unt(il) Continue execution until the line with the line number greater than the current one
  • r(eturn) Continue execution until the current function returns.
  • c(ont(inue)) Continue execution, only stop when a breakpoint is encountered.
  • j(ump) lineno Set the next line that will be executed.
  • l(ist) [first[, last]] List source code for the current file
  • a(rgs) Print the argument list of the current function
  • p expression Evaluate the expression in the current context and print its value.
  • pp expression Like the p command but using the pprint module.
  • q(uit) Quit from the debugger. The program being executed is aborted.

For a complete overview see:

http://docs.python.org/3.3/library/pdb.html