Muffinresearch Labs by Stuart Colville

Python: Debugging with PDB | 0 Comments

Posted in Code on 27th April 2008, 10:12 pm by

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!

Post Tools

GNU screen: open tab in current working directory|(1)

A nice trick for having screen open a new tab in the same directory as the one you’re currently in. To use it add it to your .screenrc

# Open new window in current dir.
bind c stuff "screen -X chdir \$PWD;screen^M"
bind ^c stuff "screen -X chdir \$PWD;screen^M"

Hat tip: mteckert on SuperUser.com

Ubuntu: add-apt-repository: command not found|(3)

When you’re using a minimal Ubuntu install if you find the ‘add-apt-repository’ command is missing (it’s useful for adding PPAs and other repositories), then simply run:

sudo apt-get install python-software-properties

Photos on Flickr

© Copyright 2004-12 Stuart Colville, all rights reserved. May contain traces of Muffin. Powered by WordPress. Hosting by Slicehost.com This page was baked in 0.462s.