0

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?

2
  • 1
    you already knew the answer ... why did you ask the question? Commented Jul 7 at 1:37
  • @jsotola It's a self-answered question, which is encouraged on Stack Overflow if it helps others: stackoverflow.com/help/self-answer. Commented Jul 7 at 1:52

1 Answer 1

0

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.