5

在 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 = ???
4

2 回答 2

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'>
于 2013-01-31T03:45:00.893 回答
1

当引发未处理的异常时,您可以使用开关ipython调用以将您转储到 python 调试器 (pdb) 中。--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

文档在pdb这里:http ://docs.python.org/2/library/pdb.html

于 2013-01-31T03:44:22.160 回答