gpt4 book ai didi

Python 兼容性 : Catching exceptions

转载 作者:太空狗 更新时间:2023-10-30 02:48:57 25 4
gpt4 key购买 nike

我有一个应用程序,它需要在所有“现代”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: 在 Python 3 中无效,except MyException as e: 在 python 2.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']

关于Python 兼容性 : Catching exceptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10568653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com