Python pdb: resume code after throwing an exception?

If I run the code with ipython %pdb magic ipython %pdb and the code throws an exception, is there a way to tell the code to continue executing subsequently?

for example, for example, an exception is ValueError: x=0 not allowed . Is it possible to set x=1 in pdb and enable code execution (resume) of the code?

+4
source share
1 answer

I donโ€™t think you can resume sending the code (i.e. the exception was really raised by calling the debugger). What you can do is put breakpoints in your code where you see errors, and this allows you to change the values โ€‹โ€‹and keep the program running, avoiding the error.

Given the script myscript.py :

 # myscript.py from IPython.core.debugger import Tracer # a callable to invoke the IPython debugger. debug_here() is like pdb.set_trace() debug_here = Tracer() def test(): counter = 0 while True: counter += 1 if counter % 4 == 0: # invoke debugger here, so we can prevent the forbidden condition debug_here() if counter % 4 == 0: raise ValueError("forbidden counter: %s" % counter) print counter test() 

which constantly increments the counter, raising an error if it is ever divisible by 4. But we edited it to drop it into the debugger, provided the error, so that we could save ourselves.

Run this script with IPython:

 In [5]: run myscript 1 2 3 > /Users/minrk/dev/ip/mine/myscript.py(14)test() 13 debug_here() ---> 14 if counter % 4 == 0: 15 raise ValueError("forbidden counter: %s" % counter) # increment counter to prevent the error from raising: ipdb> counter += 1 # continue the program: ipdb> continue 5 6 7 > /Users/minrk/dev/ip/mine/myscript.py(13)test() 12 # invoke debugger here, so we can prevent the forbidden condition ---> 13 debug_here() 14 if counter % 4 == 0: # if we just let it continue, the error will raise ipdb> continue --------------------------------------------------------------------------- ValueError Traceback (most recent call last) IPython/utils/py3compat.pyc in execfile(fname, *where) 173 else: 174 filename = fname --> 175 __builtin__.execfile(filename, *where) myscript.py in <module>() 17 print counter 18 ---> 19 test() myscript.py in test() 11 if counter % 4 == 0: 12 # invoke debugger here, so we can prevent the forbidden condition 13 debug_here() 14 if counter % 4 == 0: ---> 15 raise ValueError("forbidden counter: %s" % counter) ValueError: forbidden counter: 8 In [6]: 
+5
source

Source: https://habr.com/ru/post/1385238/


All Articles