Python Debugger Guide (pdb) – Kind of like gdb

Published on July 8, 2012

A lot of programmers starting with Python use just a plain vanilla text editor, and command line.

Although fancier IDE such as WingIDE comes with a built-in debugger, the IDE-less way of programming is still very awesome. Moreover, my  favorite IDE – Sublime Text 2 – does not support a built-in debugger..

When I first read the Python PDB from the official doc, somehow I have no patient to read it.. then I read a narrated version.

It is actually very simple to use PDB. Here’s how.

 

Step 1 – Add this code to your script

import pdb; pdb.set_trace()

This one line of code will break into the debugger from your running program.

If you are using the interactive prompt, you can also start the debugger in another way.

pdb.run('mymodule.test()')

 

Step 2 – Debug it!

This is in fact the last step :) For this, it is better to refer to this handy cheatsheet.

Python PDB Cheatsheet

 

Nonetheless, I like to highlight a few common commands:

  • n(ext) – Step over next line of code
  • Enter – Repeat the last command
  • p(rint) some_variable – Print the variable
  • l(ist) – Show the code + and – 5 lines around the current line
  • b(reak) – Show list of breakpoints
    • b 99 – Creates a breakpoint on line 99
    • clear 1 – Remove the breakpoint 1 in list (use b to see list of breakpoints)
  • !stmt – A python statement. You may change a variable value or call a function!!
  • local() – This is not a pdb command, but it can use to print out all the local variables.

 

Post-mortem – pdb.pm()

There is another pdb method that is really cool.

When you are running in interactive mode and runs into an Exception, how you wish you can stop right at that piece of culprit code, and debug.

You can! Simply run the following command, and you can can trackback to that code.

import pdb; pdb.pm()