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


当前回答

当然,看看sys。Version和sys.version_info。

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

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

在这里,系统。Version_info[0]为主版本号。sys。Version_info[1]会给你次要版本号。

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

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

其他回答

/ sys。hexversion和API和ABI Versioning:

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

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

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

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

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

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/

下面是我使用sys的一些代码。检查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)

版本检查示例如下。 注意,我没有停止执行,这段代码只是: -如果精确版本匹配,什么都不做 -如果修订(最后一个数字)不同,则写入INFO -如果major+minor不一致,则写入WARN

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)