获取当前异常的参考 [英] Get reference to the current exception

查看:88
本文介绍了获取当前异常的参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ ./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

I could not find any command in ipdb help that shows me current exception.

执行 import sys;打印sys.exc_info()不起作用。

当前,我正在这样做:

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

然后我可以使用 exc 进行分析。

then I can work with exc to analyze it.

如何轻松获得对当前有效例外的引用?

How to easily get a reference to the currently effective exception?

推荐答案

这也让我感到沮丧。我最终找到了答案此处,以及详细的说明。

This has frustrated me too for a while. I eventually found the answer here, along with a good detailed explanation.

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

The short answer is, use the ! magic prefix (!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(),保留您原来的例外。

This basically tells the debugger: "guessing wouldn't be necessary. it is python code I'm typing", thus preventing it from trying to guess what you mean by "sys", a process during which some internal exception is raised, overwriting sys.exc_info(), which used to hold your original exception.

这篇关于获取当前异常的参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆