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 simple_debugger_example.py
> /home/jmjones/debugger/simple_debugger_example.py(8)f1()
-> print some_arg (Pdb)
|
A Note on Commands Most debugger commands have abbreviations. For example, you can use either
the full command |
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
1
> /home/jmjones/svn/articles/debugger/simple_debugger_example.py(9)f1()
-> some_other_arg = some_arg + 1
(Pdb) s
> /home/jmjones/svn/articles/debugger/simple_debugger_example.py(10)f1()
-> return f2(some_other_arg)
(Pdb) s
--Call--
> /home/jmjones/svn/articles/debugger/simple_debugger_example.py(12)f2()
-> def f2(some_arg):
(Pdb) s
> /home/jmjones/svn/articles/debugger/simple_debugger_example.py(13)f2()
-> print some_arg
(Pdb) l
8 print some_arg
9 some_other_arg = some_arg + 1
10 return f2(some_other_arg)
11
12 def f2(some_arg):
13 -> print some_arg
14 some_other_arg = some_arg + 1
15 return f3(some_other_arg)
16
17 def f3(some_arg):
18 print some_arg
(Pdb)
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.