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

标签 python python-3.x debugging exception pdb

有时,我无法确定是什么时候或什么原因导致的,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/

相关文章:

python - 日志记录包的调试方法不起作用

python - 替换字节数组中的字节以修复编码

python - 如何将关键字参数作为参数传递给函数?

javascript - 抛出错误后,console.log语句无法打印?

debugging - Android Studio默认以 Debug模式启动

android - 如何让kivy小部件暂停

python - Pandas 在一列中搜索在另一列中具有不同值的重复行

Python + cx_Oracle : Unable to acquire Oracle environment handle

python - 在Python中将日期时间转换或更改为军事时间

c++ - IF 语句有奇怪的行为