Python: Debugging with PDB

Debugging anything can be a real pain in the backside. However with the right tools (think firebug) it actually can become enjoyable. The other day Rob, showed me the pdb module and after using it for two secs I was loving it.

Pdb is the python debugger. It's great because it's so simple to use; don't take my word for it, let's look at an example:

To use pdb you simply need to import it and set a breakpoint. Like so:

import pdb

Now if you add this in the middle of a piece of code and run that code. The interpreter will enter the debugger at that line.

Here's an example:

-> if int(time.time()) - os.path.getmtime(pickle_path) < self.max_age:

If I press "l" at the prompt I get some output to show where I am in the code:

(Pdb) l
127                  import pdb
128                  pdb.set_trace()
130                  # if pickle is newer than an max_age old we'll just return it
131  ->                if int(time.time()) - os.path.getmtime(pickle_path) < self.max_age:
132                      return pk
133                  # grab the etag and last mod data to use the request    
134                  else:
135                      # Use the new url if it's changed - following redirection 
136                      if url != pk['url']:

And I can start printing out vars to find out what's going on:

(Pdb) print pickle_path

There's a list of all of the pdb commands in the documentation where you can find out about all the options available.

On a side note: Pdb is also very handy for debugging Django applications as you can set a breakpoint and use the pdb prompt from where you are running the development server. Makes life a lot easier when it's a cinch to know what's going on!

comments powered by Disqus