0

When I debug a loop, the debugger quits when it encounters an error. Is it possible to stay inside the debugger so that I can investigate the program's state right before the error?

For example,

import pdb;pdb.set_trace()

for i in [1, 2, 3, 0]:
    print(2/i)

I would like to hit c so that the debugger keeps running through the loop until the last iteration. Then, instead of quitting, the debugger stays active so that I can look at what is the value of i that is causing the error.

Heisenberg
  • 8,386
  • 12
  • 53
  • 102

1 Answers1

0

What you are looking for is pdb.post_mortem. The code that may fail should be encapsulated in a try/except block, with the handler invoking that function, for example:

try:
    for i in [1, 2, 3, 0]:
        print(2/i)
except Exception:
    import pdb
    pdb.post_mortem()

Execution:

2.0
1.0
0.6666666666666666
> (3)<module>()
-> print(2/i)
(Pdb) 

The pdb shell is now at the point of failure.

metatoaster
  • 17,419
  • 5
  • 55
  • 66