在python 2.x和3.x中提高异常 [英] Raise exception in python 2.x and 3.x
问题描述
如何将此代码移植到Python 3中,以便它可以同时运行在Python 2和Python3中?
How can I port this code to Python 3 so that it would run in both, Python 2 and Python3?
raise BarException, BarException(e), sys.exc_info()[2]
(从 http://blog.ionelmc.ro/2014 / 08/03 / the-most-under-low-feature-in-python-3 / )
奖金问题 >
做一些像
Bonus question
Does it make sense to do something like
IS_PYTHON2 = sys.version_info < (3, 0)
if IS_PYTHON2:
raise BarException, BarException(e), sys.exc_info()[2]
# replace with the code that would run in Python 2 and Python 3 respectively
else:
raise BarException("Bar is closed on Christmas")
推荐答案
您将不得不使用 exec()
,因为您不能在Python中使用3参数语法3;它会引发语法错误。
You'll have to resort to using exec()
because you cannot use the 3-argument syntax in Python 3; it'll raise a syntax error.
与 six
library 已经覆盖,移植到不依赖于其他六个
定义,他们的版本看起来像这样: / p>
As always the six
library already has you covered, ported to not depend on other six
definitions their version looks like this:
import sys
if sys.version_info[0] == 3:
def reraise(tp, value, tb=None):
if value is None:
value = tp()
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
else:
exec("def reraise(tp, value, tb=None):\n raise tp, value, tb\n")
现在您可以使用:
reraise(BarException, BarException(e), sys.exc_info()[2])
,无需进一步测试Python版本。
without further testing for a Python version.
这篇关于在python 2.x和3.x中提高异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!