如何检查哪个版本的Python解释器正在运行我的脚本?


当前回答

import sys
sys.version.split(' ')[0]

sys。版本给你你想要的,只是选择第一个数字:)

其他回答

已经有几个答案建议如何查询当前的python版本。为了以编程方式检查版本需求,我将使用以下两种方法之一:

# Method 1: (see krawyoti's answer)
import sys
assert(sys.version_info >= (2,6))

# Method 2: 
import platform
from distutils.version import StrictVersion 
assert(StrictVersion(platform.python_version()) >= "2.6")

可以这样写:

#!/usr/bin/env/python
import sys
if sys.version_info<(2,6,0):
  sys.stderr.write("You need python 2.6 or later to run this script\n")
  exit(1)

在你的脚本顶部。

请注意,根据脚本中的其他内容,比目标版本更老的python甚至可能无法加载脚本,因此不会报告此错误。作为一种变通方法,您可以在一个脚本中运行上述操作,该脚本导入了更现代的代码。

import sys
sys.version.split(' ')[0]

sys。版本给你你想要的,只是选择第一个数字:)

在Windows操作系统下,通过在命令提示符中输入以下命令,验证命令的Python版本

c:\>python -V
Python 2.7.16

c:\>py -2 -V
Python 2.7.16

c:\>py -3 -V
Python 3.7.3

此外,要查看每个Python版本的文件夹配置,请运行以下命令:

For Python 2,'py -2 -m site'
For Python 3,'py -3 -m site'

只是为了好玩,下面是在CPython 1.0-3.7b2, Pypy, Jython和Micropython上的一种方法。在现代代码中,这更像是一种新奇的做法。我将其作为http://stromberg.dnsalias.org/~strombrg/pythons/的一部分编写,这是一个脚本,用于在多个版本的python上同时测试一段代码,因此您可以轻松地了解哪些python特性与哪些版本的python兼容:

via_platform = 0
check_sys = 0
via_sys_version_info = 0
via_sys_version = 0
test_sys = 0
try:
    import platform
except (ImportError, NameError):
    # We have no platform module - try to get the info via the sys module
    check_sys = 1

if not check_sys:
    if hasattr(platform, "python_version"):
        via_platform = 1
    else:
        check_sys = 1

if check_sys:
    try:
        import sys
        test_sys = 1
    except (ImportError, NameError):
        # just let via_sys_version_info and via_sys_version remain False - we have no sys module
        pass

if test_sys:
    if hasattr(sys, "version_info"):
        via_sys_version_info = 1
    elif hasattr(sys, "version"):
        via_sys_version = 1
    else:
        # just let via_sys remain False
        pass

if via_platform:
    # This gives pretty good info, but is not available in older interpreters.  Also, micropython has a
    # platform module that does not really contain anything.
    print(platform.python_version())
elif via_sys_version_info:
    # This is compatible with some older interpreters, but does not give quite as much info.
    print("%s.%s.%s" % sys.version_info[:3])
elif via_sys_version:
    import string
    # This is compatible with some older interpreters, but does not give quite as much info.
    verbose_version = sys.version
    version_list = string.split(verbose_version)
    print(version_list[0])
else:
    print("unknown")