我有一个应用程序,需要在所有的“现代”Python版本中工作,这意味着2.5-3.2。我不想要两个代码库,所以2to3不是一个选择。
考虑一下这样的情况:
def func(input):
if input != 'xyz':
raise MyException(some_function(input))
return some_other_function(input)如何捕获这个异常,以访问异常对象?except MyException, e:在Python3中无效,except MyException as e:在Python2.5中无效。
显然,返回异常对象是可能的,但我希望我不必这么做。
发布于 2012-05-13 09:37:40
这个问题在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']https://stackoverflow.com/questions/10568653
复制相似问题