在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 = ???
解决方法:
您可以使用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'>