获取对当前异常的引用

war*_*iuc 12 python debugging exception pdb ipdb

$ ./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> 
Run Code Online (Sandbox Code Playgroud)

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

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

目前我这样做:

try:
    do_something_that_raises_an_exception()
except Exception as exc:
    import ipdb; ipdb.set_trace()
Run Code Online (Sandbox Code Playgroud)

然后我可以exc用来分析它.

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

shx*_*hx2 26

这让我有点沮丧.我最终在这里找到了答案,还有一个很好的详细解释.

简短的回答是,使用!魔术前缀(!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>)
Run Code Online (Sandbox Code Playgroud)

这基本上告诉调试器:"猜测不是必需的.它是我正在键入的python代码",从而阻止它试图猜测"sys"是什么意思,在这个过程中会引发一些内部异常,覆盖sys.exc_info(),曾用于保存您的原始例外.

  • 谢谢!我最终把'alias exc_info!import sys; sys.exc_info()`进入`〜/ .pdbrc` (5认同)
  • 谢谢,这有效。我希望有一个内置的“ipdb”命令,否则我必须输入:“!import sys;” sys.exc_info()` (2认同)
  • 这适用于 pdb 和 ipdb。要分配给变量,您可以使用`!import sys; exc=sys.exc_info()` 然后你可以探索它,导入`traceback`并打印它等。 (2认同)