The Python Debugger

pdb

pdb is the Python debugger (others are also available!)

We generally invoke it as a script to run other scripts:

python3 -m pdb myscript.py

We can also use it to switch to debugging part way through a program by importing the pdb class and calling the set_trace() method at the location where you want to start debugging:

import pdb; pdb.set_trace()

You can then step through the code following this statement, and continue running without the debugger using the continue command.

Basic commands

Command Effect
hObtain help on commands
nexecutes the next line of code (skips over subroutines)
ssteps into a subroutine
llist lines of code. Optionally specify a range of lines (e.g. l 10,20). Otherwise will list from the current line.
pprint the contents of a variable (e.g. p a)
bbreak the execution of the code at a specified line (e.g. b 32) or function (e.g. myfunc). Without arguments, list the break points
clDelete a specified breakpoint (e.g. cl 1) or all break points (cl - asks for confirmation)
ccontinue execution until a breakpoint, or the end of the code, is reached
qquit

For more details see https://docs.python.org/3/library/pdb.html.

Try it out on this example code [example1.py].

Continue