在python和/或ipython交互式解释器中,如何在最后一个未处理的异常上绑定名称?即相当于
>>> try:
... 1/0
... except Exception as potato:
... pass
...
>>> format(potato)
'integer division or modulo by zero'
必须是......
>>> 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> import sys
>>> potato = ???
答案 0 :(得分:5)
您可以使用sys.last_value
:
>>> 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> sys.last_value
ZeroDivisionError('integer division or modulo by zero',)
>>> type(sys.last_value)
<type 'exceptions.ZeroDivisionError'>
答案 1 :(得分:1)
您可以使用ipython
开关调用--pdb
,以便在出现未处理的异常时将您转储到python调试器(pdb)中。
$ ipython --pdb
In [1]: 1/0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-2-05c9758a9c21> in <module>()
----> 1 1/0
ZeroDivisionError: integer division or modulo by zero
> /usr/lib/python2.7/bdb.py(177)_set_stopinfo()
176 def _set_stopinfo(self, stopframe, returnframe, stoplineno=0):
--> 177 self.stopframe = stopframe
178 self.returnframe = returnframe
ipdb> whatis
*** SyntaxError: SyntaxError('unexpected EOF while parsing', ('<string>', 0, 0, ''))
ipdb> where
/usr/lib/python2.7/bdb.py(43)reset()
41 linecache.checkcache()
42 self.botframe = None
---> 43 self._set_stopinfo(None, None)
44
45 def trace_dispatch(self, frame, event, arg):
> /usr/lib/python2.7/bdb.py(177)_set_stopinfo()
175
176 def _set_stopinfo(self, stopframe, returnframe, stoplineno=0):
--> 177 self.stopframe = stopframe
178 self.returnframe = returnframe
179 self.quitting = 0