4

我有一個應用程序,需要在所有「現代」Python版本中工作,這意味着2.5-3.2。我不想要兩個代碼庫,所以2to3不是一個選項。Python兼容性:捕獲異常

考慮這樣的事情:

def func(input): 
    if input != 'xyz': 
     raise MyException(some_function(input)) 
    return some_other_function(input) 

我怎麼能捕獲此異常,以訪問異常對象? except MyException, e:在Python 3中無效,except MyException as e:在python 2.5中無效。

很明顯,它可能有可能返回異常對象,但我希望,我不必這樣做。

回答

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']