How to use PDB Python debugger

When the Python interpreter encounters an error or exceptional condition while running your code, it quits the program and prints a stack trace. I typically would like to inspect the stack at the point of error to figure out the cause of it. It would be nice to print out some of the local variables you suspect at that point, walk up the stack frames to the calling functions and inspect some of their variables too. All of this is easily possible in Python by using the Python debugger module!

  • You can run your script with the pdb module using any one of these commands:
$ pdb

$ python -m pdb

$ pdb3

$ python3 -m pdb

When run explicitly like this, PDB will stop at the first function.

  • Alternatively, you can make the Python interpreter to invoke the debugger and stop at a line by adding to the code and running that script:
import pdb; pdb.set_trace()
  • Once your program has stopped, you can add more breakpoints, step through the code and inspect variables. For the entire list of commands available at the debugger, see PDB documentation. You will notice that they are similar (but not the same) as GDB commands.

  • Some of the most common commands are: b to set breakpoints, c to continue execution, w to inspect the stack trace, u and d to move up and down the call stack.

  • To move through code, s to step into functions, n to execute the next statement and return to return from methods.

  • To print out variables or values, use the p command. For example:

p foobar
p type(foobar)
  • You can even execute statements that assign to new or existing variables and call methods at the debugger prompt.

  • If you need tab completion, colorful syntax highlighting and other interactive features, then I recommend using IPDB. It is a drop-in replacement for pdb.

Installing it is easy:

$ sudo apt install python-ipdb
$ sudo apt install python3-ipdb

Using it is similar to PDB:

$ ipdb

$ python -m ipdb

$ ipdb3

$ python3 -m ipdb

Tried with: Python 3.5.1 and Ubuntu 16.04

2 thoughts on “How to use PDB Python debugger

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.