如何在运行时检测Python版本?

我有一个Python文件,它可能必须支持Python版本<3.X和>= 3.x。是否有一种方法可以内省Python运行时,以了解它正在运行的版本(例如,2.6 or 3.2.x)?

356462 次浏览

当然,看看sys.versionsys.version_info

例如,要检查您正在运行Python 3。x,使用

import sys
if sys.version_info[0] < 3:
raise Exception("Must be using Python 3")

这里,sys.version_info[0]是主版本号。sys.version_info[1]会给你次要版本号。

在Python 2.7及更高版本中,sys.version_info的组件也可以通过名称访问,所以主版本号是sys.version_info.major

另见如何在使用新语言特性的程序中检查Python版本?

根据sys.hexversionAPI和ABI版本控制:

import sys
if sys.hexversion >= 0x3000000:
print('Python 3.x hexversion %s is in use.' % hex(sys.hexversion))

下面是我使用sys.version_info检查Python安装的一些代码:

def check_installation(rv):
current_version = sys.version_info
if current_version[0] == rv[0] and current_version[1] >= rv[1]:
pass
else:
sys.stderr.write( "[%s] - Error: Your Python interpreter must be %d.%d or greater (within major version %d)\n" % (sys.argv[0], rv[0], rv[1], rv[0]) )
sys.exit(-1)
return 0


...


# Calling the 'check_installation' function checks if Python is >= 2.7 and < 3
required_version = (2,7)
check_installation(required_version)

为了使脚本与Python2和3兼容,我使用:

from sys import version_info
if version_info[0] < 3:
from __future__ import print_function

试试这段代码,应该可以工作:

import platform
print(platform.python_version())

最佳解决方案取决于有多少代码是不兼容的。如果有很多地方需要支持Python 2和3,six是兼容性模块。如果你想检查版本,six.PY2six.PY3是两个布尔值。

然而,比使用大量if语句更好的解决方案是尽可能使用six兼容函数。假设,如果Python 3000有一个新的next语法,有人可以更新six,这样你的旧代码仍然可以工作。

import six


# OK
if six.PY2:
x = it.next() # Python 2 syntax
else:
x = next(it) # Python 3 syntax


# Better
x = six.next(it)

http://pythonhosted.org/six/

版本检查示例如下 注意,我没有停止执行,这个代码片段只是:
-如果精确版本匹配
,什么都不做 -如果revision (last number)不同,则写入INFO
—如果major+minor中任意一个不一致

import sys
import warnings


def checkVersion():
# Checking Python version:
expect_major = 2
expect_minor = 7
expect_rev = 14
if sys.version_info[:3] != (expect_major, expect_minor, expect_rev):
print("INFO: Script developed and tested with Python " + str(expect_major) + "." + str(expect_minor) + "." + str(expect_rev))
current_version = str(sys.version_info[0])+"."+str(sys.version_info[1])+"."+str(sys.version_info[2])
if sys.version_info[:2] != (expect_major, expect_minor):
warnings.warn("Current Python version was unexpected: Python " + current_version)
else:
print("      Current version is different: Python " + current_version)
因为所有你感兴趣的是你是否有Python 2或3,这有点粗糙,但绝对是最简单和100%的工作方式如下: python <代码> Python_version_major = 3/2*2 这样做的唯一缺点是,当有Python 4时,它可能仍然会给你3。< / p >

如果你想以人类可读的形式看到所有血腥的细节,你可以使用:

import platform;


print(platform.sys.version);

我的系统输出:

3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0]

一些非常详细但机器可解析的内容将是从platform.sys中获取version_info对象,然后使用其属性执行预先确定的操作过程。例如:

import platform;


print(platform.sys.version_info)

系统输出:

sys.version_info(major=3, minor=6, micro=5, releaselevel='final', serial=0)