我有一个应用程序,需要在所有“现代”Python版本中工作,这意味着2.5
- 3.2
。我不想要两个代码库,因此2to3
不是一个选项。
考虑这样的事情:
def func(input):
if input != 'xyz':
raise MyException(some_function(input))
return some_other_function(input)
如何捕获此异常,以获取对异常对象的访问权限?
{3}中的except MyException, e:
无效,except MyException as e:
在python 2.5中无效。
显然可以返回异常对象,但我希望,我不必这样做。
答案 0 :(得分:5)
解决了这个问题in the Py3k docs。解决方案是检查sys.exc_info():
from __future__ import print_function
try:
raise Exception()
except Exception:
import sys
print(sys.exc_info()) # => (<type 'exceptions.Exception'>, Exception(), <traceback object at 0x101c39830>)
exc = sys.exc_info()[1]
print(type(exc)) # => <type 'exceptions.Exception'>
print([a for a in dir(exc) if not a.startswith('__')]) # => ['args', 'message']