【问题标题】:python pdb: resume code execution after exception caught?python pdb:捕获异常后恢复代码执行?
【发布时间】:2011-12-07 22:38:13
【问题描述】:

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

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

【问题讨论】:

    标签: ipython pdb


    【解决方案1】:

    我认为您无法在事后恢复代码(即异常实际上已引发,触发调试器的调用)。你可以做的,就是在你看到错误的代码中放置断点,这样你就可以改变值,并继续程序以避免错误。

    给定一个脚本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-03-01
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多