Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get reference to the current exception

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

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

Doing import sys; print sys.exc_info() doesn't work.

Currently I do:

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

then I can work with exc to analyze it.

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

like image 436
warvariuc Avatar asked Dec 27 '13 09:12

warvariuc


1 Answers

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

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

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.

like image 171
shx2 Avatar answered Nov 17 '22 00:11

shx2