有一个python代码,应该支持Python 3,但可能会在Python 2.7中运行,也可能不会运行。
例如,此代码片段可以在Python 2.7和Python 3中运行。
即使代码在Python 2.7上运行良好,在严格模式下强制和推荐Python 3兼容性的标准方法是什么?

print('This file works in both')
print('How to throw an exception,and suggest recommendation of python 3 only ?')

Python 2.7:https://ideone.com/bGnbvd

Python 3.5:https://ideone.com/yrTi3p

可以有多种hack和异常(exception),它们可以在Python 3中工作,而不能在Python 2.7中工作,可以用来实现此目的。
我正在文件/模块/项目的开头寻找最推荐的方法。

最佳答案

如果它是带有setup.py的正确Python包,则可以使用以下几种方法:

  • python_requires classifier



    示例:python_requires='>=3',
  • 由于相对较新地添加了对python_requires分类器的支持,因此您应该考虑使用较旧版本的pipsetuptools安装软件包的用户。在这种情况下,您可以检查sys.version_info文件 setup.py 中的like Django does:
    import sys
    
    CURRENT_PYTHON = sys.version_info[:2]
    REQUIRED_PYTHON = (3, 5)
    
    # This check and everything above must remain compatible with Python 2.7.
    if CURRENT_PYTHON < REQUIRED_PYTHON:
        sys.stderr.write("""...""")
        sys.exit(1)
    
  • Programming Language Python version classifiers:
    'Programming Language :: Python',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.5',
    'Programming Language :: Python :: 3.6',
    'Programming Language :: Python :: 3 :: Only',
    

  • 而且,作为奖励,如果通过PyPI软件包索引分发软件包,则python_requires和其他分类器将显示在package home page上。

    关于python - 为Python模块推荐 "Python 3 only"兼容性的标准方法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48113250/

    10-12 17:19
    查看更多