Python 2.x和3.x中的有效语法用于引发异常?
作者:互联网
如何将此代码移植到Python 3,以便它可以在Python 2和Python 3中运行?
raise BarException, BarException(e), sys.exc_info()[2]
(从http://blog.ionelmc.ro/2014/08/03/the-most-underrated-feature-in-python-3/复制)
奖金问题
做一些类似的事情是否有意义
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参数语法;它会引发语法错误.
一如既往six
library已经覆盖了你,移植到不依赖于其他六个定义,他们的版本看起来像这样:
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版本.
标签:python,python-3-x,exception,python-2-x 来源: https://codeday.me/bug/20191006/1858296.html