python pdb:异常捕获后恢复代码执行?

kef*_*ich 4 ipython pdb

如果我在ipython %pdb启用魔法的情况下运行代码并且代码抛出异常,是否有任何方法可以告诉代码继续执行?

例如,说例外是a ValueError: x=0 not allowed.我可以在pdb中设置x=1并允许代码继续(恢复)执行吗?

min*_*nrk 5

我不认为你可以恢复代码验证(即实际引发异常,触发调试器的调用).您可以做的是,在您看到错误的代码中放置断点,并允许您更改值,并继续程序以避免错误.

给定一个脚本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()
Run Code Online (Sandbox Code Playgroud)

这会不断增加一个计数器,如果它可以被4整除则会产生错误.但是我们已经编辑它以在错误条件下进入调试器,所以我们可以保存自己.

从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]:
Run Code Online (Sandbox Code Playgroud)