Cheat sheet for debugging python code with pdb.

Start pdb Link to this heading

python
1import pdb
2pdb.set_trace()

This command will create a breakpoint in your code. When the code reaches this point, it will stop and you will be able to debug it. The cmd line will look like this:

bash
1(Pdb) # here you can type commands, or check the value of variables

pdb commands Link to this heading

Check the source code Link to this heading

bash
1(Pdb) l # list 11 lines of code around the current line
bash
1(Pdb) ll # list the whole function

Step next Link to this heading

Command Description
n step next (will not go into functions)
s step into (will go into functions)
r step out (will go out of functions)

Check variables Link to this heading

bash
1(Pdb) p <variable> # print the value of a variable

Actually, you can use any python code here, for example:

bash
1(Pdb) p [x for x in range(10)] # print a list

p is not necessary, you can just type the code and it will be executed.

Other commands Link to this heading

Command Description
c continue execution (will stop at the next breakpoint)
q quit the debugger (will stop the execution)
a print the argument list of the current function
whatis <variable> print the type of a variable

References Link to this heading