Python DevCenter
oreilly.comSafari Books Online.Conferences.


Interactive Debugging in Python
Pages: 1, 2, 3, 4, 5, 6, 7

Example Usage

Now that I've shown you how to get into a debugging session, it's time for a simple example. The Python standard library reference documentation includes the Python debugger commands, but I will go over commands as I introduce them. The following example script starts by calling f1(), which calls f2(), which calls f3(), which calls f4(), and then returns back up the chain. Running the script immediately drops into a debugging session:

#!/usr/bin/env python

import pdb

def f1(some_arg):
    print some_arg
    some_other_arg = some_arg + 1
    return f2(some_other_arg)

def f2(some_arg):
    print some_arg
    some_other_arg = some_arg + 1
    return f3(some_other_arg)

def f3(some_arg):
    print some_arg
    some_other_arg = some_arg + 1
    return f4(some_other_arg)
def f4(some_arg):
    print some_arg
    some_other_arg = some_arg + 1
    return some_other_arg

if __name__ == "__main__":
    pdb.runcall(f1, 1)

When I run this piece of code, I immediately get a (Pdb) prompt, like this:

jmjones@bean:~/debugger $ python
> /home/jmjones/debugger/
-> print some_arg (Pdb)

A Note on Commands

Most debugger commands have abbreviations. For example, you can use either the full command step or its abbreviation s. When I introduce a command, I will put parentheses around the abbreviation. Continuing the step example, I will introduce step as (s)tep. You can find all commands and their abbreviations on the debugger command page of the Python standard library documentation referenced above.

First, I wanted to step way down to f2() using the (s)tep command, and then see where I was with the (l)ist command:

(Pdb) s
> /home/jmjones/svn/articles/debugger/
-> some_other_arg = some_arg + 1
(Pdb) s
> /home/jmjones/svn/articles/debugger/
-> return f2(some_other_arg)
(Pdb) s
> /home/jmjones/svn/articles/debugger/
-> def f2(some_arg):
(Pdb) s
> /home/jmjones/svn/articles/debugger/
-> print some_arg
(Pdb) l
  8         print some_arg
  9         some_other_arg = some_arg + 1
 10         return f2(some_other_arg)
 12     def f2(some_arg):
 13  ->     print some_arg
 14         some_other_arg = some_arg + 1
 15         return f3(some_other_arg)
 17     def f3(some_arg):
 18         print some_arg

The step command executes the next piece of code that it can and returns a debugger prompt. If the next piece of code to execute is inside a function, it steps inside the function. The list command shows five lines above and five lines below the debugger's current position in the code. The list command above shows that the debugger is on line 13 with the -> characters. Instead of repeating the step command, I could have just pressed Enter, which repeats the previous command.

Pages: 1, 2, 3, 4, 5, 6, 7

Next Pagearrow

Sponsored by: