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
pdb.set_trace()

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:

>/Users/code/Python/transmission/transmission.py(131)txcache()
-> if int(time.time()) - os.path.getmtime(pickle_path) < self.max_age:
(Pdb) 

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

(Pdb) l
126  	            
127  	            import pdb
128  	            pdb.set_trace()
129  	            
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']:
(Pdb) 

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

(Pdb) print pickle_path
/var/folders/v6/v6hHYTmrGBKMrHtAaaWVek+++TM/-Tmp-/e123005fdf1bfd64848c0744ec110f45
(Pdb) 

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!

Show Comments