I am debugging a code in Python using Pdb
:
a = [12, 3, 4, 10, 23, 1]
def compute(x):
return 2 * x
for i in a:
b = compute(i)
To trace the value of a variable inside the loop, I set a breakpoint at the first line of the loop body and use the continue
command to move to the next breakpoint, then use print
command to inspect the variable:
$ python -m pdb program.py
> /tmp/program.py(1)<module>()
-> a = [12, 3, 4, 10, 23, 1]
(Pdb) l
1 -> a = [12, 3, 4, 10, 23, 1]
2
3
4 def compute(x):
5 return 2 * x
6
7
8 for i in a:
9 b = compute(i)
[EOF]
(Pdb) b 9
Breakpoint 1 at /tmp/program.py:9
(Pdb) c
> /tmp/program.py(9)<module>()
-> b = compute(i)
(Pdb) p i
12
(Pdb) c
> /tmp/program.py(9)<module>()
-> b = compute(i)
(Pdb) p i
3
(Pdb) c
> /tmp/program.py(9)<module>()
-> b = compute(i)
(Pdb) p i
4
(Pdb)
Is there any way to automatically print the variable's value every time execution stops at the breakpoint?
Yes, It can be done using display
command. Use it as follows:
(Pdb) display variable
This command will automatically show the current and previous values of the variable each time the debugger stops:
$ python -m pdb program.py
> /tmp/program.py(1)<module>()
-> a = [12, 3, 4, 10, 23, 1]
(Pdb) b 9
Breakpoint 1 at /tmp/program.py:9
(Pdb) c
> /tmp/program.py(9)<module>()
-> b = compute(i)
(Pdb) display i
display i: 12
(Pdb) c
> /tmp/program.py(9)<module>()
-> b = compute(i)
display i: 3 [old: 12]
(Pdb) c
> /tmp/program.py(9)<module>()
-> b = compute(i)
display i: 4 [old: 3]
(Pdb) c
> /tmp/program.py(9)<module>()
-> b = compute(i)
display i: 10 [old: 4]
(Pdb) c
> /tmp/program.py(9)<module>()
-> b = compute(i)
display i: 23 [old: 10]