python - sys.version_info 对于 Python 版本检查是否可靠?

标签 python python-3.x python-2.7

如果我正在制作一个我想在 Python 2 中运行与在 Python 3 中相同的模块,那么有很多选项,包括 six , futures , 和 2to3 .如果更改的数量很少,那么这些工具中的每一个都有足够的怪癖,我倾向于只为我的模块实际使用的少数不兼容功能编写一个兼容接口(interface)。

一个合理的标准方法是使用简单的版本检查。

import module_bar

if sys.version_info >= (3,):
    uniformly_named_foo = module_bar.py3_thing
else:
    uniformly_named_foo = module_bar.py2_thing

是否有任何奇怪的案例 sys.version_info不会正确报告尽管?过去,我已经被格式错误的路径、配置、安装、修改等等所困扰,以至于我觉得这不是我应该信任的事情。

当我们深入了解它时,我真正关心的是是否实现了特定功能 .在 Web 开发中,嗅探用户代理通常被认为是一种不好的做法。相反,人们应该尽最大努力确定某个特定功能是否正在使用中。根据功能的不同,有很多方法可以实现这一点。
if hasattr(module_bar, 'py3_thing'):
    uniformly_named_foo = module_bar.py3_thing
else:
    uniformly_named_foo = module_bar.py2_thing

在我的机器上,第二条路线的速度要慢两倍(对于一次性操作来说,额外的几百纳秒并不重要),但它似乎没有任何其他主要缺点。不过有优势吗? 是否存在第二种方法会成功而第一种方法会失败的 Python 安装?

最佳答案

是的。 sys.version_info是确定 Python 版本的可靠方法。

Python 3 documentationPython 2 documentation .

注:sys.version_info是可靠的,但不是 sys.version :

sys.version

A string containing the version number of the Python interpreter plus additional information on the build number and compiler used. This string is displayed when the interactive interpreter is started. Do not extract version information out of it, rather, use version_info and the functions provided by the platform module.



如果您担心坏模块会改变 sys.version_info 的值或者别的,你可以强制重新加载 <module 'sys' (built-in)> :
import sys
sys.version_info = "boo"
print(sys.version_info)  # boo

sys.modules.pop("sys")
import sys  # reloaded
print(sys.version_info)
# Output: sys.version_info(major=3, minor=6, ...

关于python - sys.version_info 对于 Python 版本检查是否可靠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52359805/

相关文章:

python - 安装IbPy以在spyder(anaconda)中使用

python - 如何在 python 3 中解析 excel 文档中的文本?

python - Tensorflow 对象检测 API : Multiple Objects coordinates

python - 在python中的不同LAN之间发送数据

python - 使用json解析空字符串

python - 如何删除通过 Appengine 中的 Key 属性连接的实体连接的所有实体

python - python中有对应 "\"的函数吗?

python - 有没有更快的方法来添加两个二维 numpy 数组

python - shutil make_archive 生成​​嵌套的 .zip 文件

python - 负数楼层划分