【问题标题】:Get reference to the current exception获取对当前异常的引用
【发布时间】:2014-01-14 21:10:15
【问题描述】:
$ ./runtests.py -v tests/managers/test_customer.py:CustomerManagerTest.test_register_without_subscription --ipdb

...

test_register_without_subscription (tests.managers.test_customer.CustomerManagerTest) ... 
- TRACEBACK --------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python2.7/unittest/case.py", line 331, in run
    testMethod()
  File "*****/tests/managers/test_customer.py", line 198, in test_register_without_subscription
    1/0
ZeroDivisionError: integer division or modulo by zero
--------------------------------------------------------------------------------
> *****/tests/managers/test_customer.py(198)test_register_without_subscription()
    197     def test_register_without_subscription(self):
--> 198         1/0
    199         ...

ipdb> import sys
ipdb> sys.exc_info()
(<type 'exceptions.AttributeError'>, AttributeError("Pdb instance has no attribute 'do_sys'",), <traceback object at 0x47eb908>)
ipdb> 

我在ipdb help 中找不到任何显示当前异常的命令。

import sys; print sys.exc_info() 不起作用。

目前我这样做:

try:
    do_something_that_raises_an_exception()
except Exception as exc:
    import ipdb; ipdb.set_trace()

然后我可以和exc一起分析它。

如何轻松获得对当前有效异常的引用?

【问题讨论】:

  • 看起来这可能已经在这里得到了回答:stackoverflow.com/a/19211195/399704
  • @AaronD,您链接中的答案仅适用于pdb,不适用于ipdb...
  • @AaronD,当我尝试在except 中检索sys.last_value 时,我得到AttributeError: 'module' object has no attribute 'last_value'bugs.python.org/issue6307

标签: python debugging exception pdb ipdb


【解决方案1】:

这也让我沮丧了一段时间。我最终找到了答案here,以及一个很好的详细解释。

简短的回答是,使用 ! 魔术前缀 (!sys.exc_info()):

In [4]: 1/0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
...
ipdb> !sys.exc_info()
(<type 'exceptions.AttributeError'>, AttributeError("'exceptions.ZeroDivisionError' object has no attribute '_render_traceback_'",), <traceback object at 0x101c55fc8>)

这基本上告诉调试器:“猜测没有必要。这是我正在输入的python代码”,从而防止它试图猜测“sys”的含义,在此过程中出现一些内部异常引发,覆盖 sys.exc_info(),用于保存您的原始异常。

【讨论】:

  • 谢谢,这行得通。我希望有一个内置的ipdb 命令,否则我必须输入:!import sys; sys.exc_info()
  • @warwaruk 你可以在你的.pdbrc中定义一个别名
  • 谢谢!我最终将alias exc_info !import sys; sys.exc_info() 放入~/.pdbrc
  • 这适用于 pdb 和 ipdb。要分配给一个变量,你可以使用!import sys; exc=sys.exc_info()然后你可以探索它,导入traceback并打印它等等。
  • 非常有帮助!仅供参考,您获得想法的链接不再指向任何相关内容。
猜你喜欢
  • 2013-07-31
  • 2023-02-01
  • 2012-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-08
相关资源
最近更新 更多