有一个python代码,它应该支持Python 3,但可能会也可能不会在Python 2.7中运行。例如,此代码段可以在 Python 2.7 和 Python 3 中运行。在严格模式下强制和推荐 Python 3 兼容性的标准方法是什么,即使代码在 Python 2.7 上运行良好?
print('This file works in both')
print('How to throw an exception,and suggest recommendation of python 3 only ?')
蟒蛇 2.7 : https://ideone.com/bGnbvd
Python 3.5 : https://ideone.com/yrTi3p
可以有多个黑客和异常,它们在Python 3中有效,而在Python 2.7中则不然,后者可用于实现这一点。我正在寻找在文件/模块/项目开头最推荐的方法。
如果它是一个合适的 Python 包,带有 setup.py
,你可以使用几样东西:
-
python_requires
分类器如果您的项目仅在某些 Python 版本上运行,则将
python_requires
参数设置为相应的 PEP 440 版本说明符字符串将阻止 pip 在其他 Python 版本上安装该项目。示例:
python_requires='>=3',
-
由于对
python_requires
分类器的支持是最近添加的,因此您应该考虑使用旧版本的pip
和setuptools
安装包的用户。在这种情况下,你可以像 Django 一样检查setup.py
文件中的sys.version_info
: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 版本分类器:'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
和其他分类器将显示在包主页上。
简单地检查sys.version_info
:
import sys
if sys.version_info[0] < 3:
raise SystemExit("Use Python 3 (or higher) only")