7

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

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

4

1 回答 1

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]:
于 2011-12-08T00:10:33.703 回答