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

Why can't pdb access a variable containing an exception?

有时,我无法确定是什么时候或什么原因导致的,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() 有效地退出块,因此执行上面的隐式 finally 套件。

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

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",)