gpt4 book ai didi

python - 为什么 pdb 不能访问包含异常的变量?

转载 作者:太空狗 更新时间:2023-10-29 20:55:42 26 4
gpt4 key购买 nike

有时,我无法确定是什么时候或什么原因导致的,pdb 不会帮助您编写如下代码:

try:
foo()
except Exception as e:
import pdb; pdb.set_trace()

您最终会得到通常的提示,但尝试访问 e 将导致:

(pdb) e
*** NameError: name 'e' is not defined.

当然不是所有时候都这样,在linux、windows、我的机器、我同事的机器上...

最佳答案

在 Python 3 中,except .. as target 语句的目标在套件退出时被清除。来自try statement documentation :

When an exception has been assigned using as target, it is cleared at the end of the except clause. This is as if

except E as N:
foo

was translated to

except E as N:
try:
foo
finally:
del N

This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs.

调用 pdb.set_trace() 有效地退出 block ,因此执行上面的隐式 finally 套件。

将异常绑定(bind)到不同的名称:

try:
foo()
except Exception as e:
exception = e
import pdb; pdb.set_trace()

演示:

>>> try:
... foo()
... except Exception as e:
... exception = e
... import pdb; pdb.set_trace()
...
--Return--
> <stdin>(5)<module>()->None
(Pdb) e
*** NameError: name 'e' is not defined
(Pdb) exception
NameError("name 'foo' is not defined",)

关于python - 为什么 pdb 不能访问包含异常的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38672560/

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