gpt4 book ai didi

ipython - python pdb : resume code execution after exception caught?

转载 作者:行者123 更新时间:2023-12-03 16:29:58 25 4
gpt4 key购买 nike

如果我使用 ipython %pdb 运行代码启用魔法并且代码抛出异常,有什么方法可以告诉代码之后继续执行吗?

例如,假设异常是 ValueError: x=0 not allowed .我可以在 pdb 中设置 x=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]:

关于ipython - python pdb : resume code execution after exception caught?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8423637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com