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

时间:2011-12-07 22:38:13

标签: ipython pdb

如果我运行启用了ipython %pdb魔法的代码并且代码抛出异常,有没有办法告诉代码继续执行?

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

1 个答案:

答案 0 :(得分: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()

它会不断递增计数器,如果它可以被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]: