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!

  • After you see a Python script fail, just run it again but using the pdb module using any one of these commands:
$ pdb

$ python -m pdb

$ pdb3

$ python3 -m pdb
  • If you do not want to run the PDB module like this, you can also add a hard breakpoint at a line in your code by adding this before that line:
import pdb; pdb.set_trace()
  • When run explicitly, PDB will stop at the first function. This is a good point to set breakpoints using the b command.
  • Press c to continue execution. It will run the script and should fail at the place where it had failed earlier.
  • Press w to inspect the stack trace. Your current frame will be indicated by an arrow. To move up and down the stack, use u and d.
  • To print out the values of variables in the current stack frame, use the p command, type their name and press Enter.
  • For the entire list of commands available at the debugger, see PDB documentation.
  • If you need tab completion, colorful syntax highlighting and other interactive features, then install the IPDB module which builds upon IPython to offer these features. Using that is similar to PDB:
$ ipdb

$ python -m ipdb

$ ipdb3

$ python3 -m ipdb

Happy debugging!šŸ™‚

Tried with: Python 3.5.1 and Ubuntu 16.04

One thought 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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s