简体   繁体   English

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

[英]How do I check which version of Python is running my script?

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

This information is available in the sys.version string in the sys module:此信息在sys模块中的sys.version字符串中可用:

>>> import sys

Human readable:人类可读:

>>> print(sys.version)  # parentheses necessary in python 3.       
2.5.2 (r252:60911, Jul 31 2008, 17:28:52) 
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]

For further processing, use sys.version_info or sys.hexversion :如需进一步处理,请使用sys.version_infosys.hexversion

>>> sys.version_info
(2, 5, 2, 'final', 0)
# or
>>> sys.hexversion
34014192

To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code:要确保脚本以最低版本的 Python 解释器运行,请将其添加到您的代码中:

assert sys.version_info >= (2, 5)

This compares major and minor version information.这将比较主要和次要版本信息。 Add micro (= 0 , 1 , etc) and even releaselevel (= 'alpha' , 'final' , etc) to the tuple as you like.根据需要将 micro (= 0 , 1等) 甚至 releaselevel (= 'alpha' , 'final'等) 添加到元组中。 Note however, that it is almost always better to "duck" check if a certain feature is there, and if not, workaround (or bail out).但是请注意,“躲避”检查某个功能是否存在几乎总是更好,如果没有,解决方法(或纾困)。 Sometimes features go away in newer releases, being replaced by others.有时功能会在新版本中消失,被其他功能取代。

From the command line (note the capital 'V'):从命令行(注意大写“V”):

python -V

This is documented in 'man python'.这记录在“man python”中。

From IPython console从 IPython 控制台

!python -V

I like sys.hexversion for stuff like this.我喜欢sys.hexversion这样的东西。

>>> import sys
>>> sys.hexversion
33883376
>>> '%x' % sys.hexversion
'20504f0'
>>> sys.hexversion < 0x02060000
True

Use platform 's python_version from the stdlib:使用来自 stdlib platformpython_version

from platform import python_version
print(python_version())

# 3.9.2

Your best bet is probably something like so:你最好的选择可能是这样的:

>>> import sys
>>> sys.version_info
(2, 6, 4, 'final', 0)
>>> if not sys.version_info[:2] == (2, 6):
...    print "Error, I need python 2.6"
... else:
...    from my_module import twoPointSixCode
>>> 

Additionally, you can always wrap your imports in a simple try, which should catch syntax errors.此外,您始终可以将导入包装在一个简单的尝试中,这应该会捕获语法错误。 And, to @Heikki's point, this code will be compatible with much older versions of python:而且,就@Heikki 而言,这段代码将与更旧版本的python 兼容:

>>> try:
...     from my_module import twoPointSixCode
... except Exception: 
...     print "can't import, probably because your python is too old!"
>>>

Put something like:放一些类似的东西:

#!/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)

at the top of your script.在脚本的顶部。

Note that depending on what else is in your script, older versions of python than the target may not be able to even load the script, so won't get far enough to report this error.请注意,根据脚本中的其他内容,比目标更旧的 python 版本可能甚至无法加载脚本,因此不会报告此错误。 As a workaround, you can run the above in a script that imports the script with the more modern code.作为一种解决方法,您可以在一个脚本中运行上述内容,该脚本使用更现代的代码导入脚本。

Here's a short commandline version which exits straight away (handy for scripts and automated execution):这是一个简短的命令行版本,它会立即退出(方便脚本和自动执行):

python -c "print(__import__('sys').version)"

Or just the major, minor and micro:或者只是主要的,次要的和微观的:

python -c "print(__import__('sys').version_info[:1])" # (2,)
python -c "print(__import__('sys').version_info[:2])" # (2, 7)
python -c "print(__import__('sys').version_info[:3])" # (2, 7, 6)

With six module, you can do it by:使用six模块,您可以通过以下方式完成:

import six

if six.PY2:
  # this is python2.x
else:
  # six.PY3
  # this is python3.x
import sys
sys.version.split(' ')[0]

sys.version gives you what you want, just pick the first number :) sys.version 为您提供您想要的,只需选择第一个数字 :)

Like Seth said, the main script could check sys.version_info (but note that that didn't appear until 2.0, so if you want to support older versions you would need to check another version property of the sys module).就像 Seth 所说,主脚本可以检查sys.version_info (但请注意,直到 2.0 才出现,所以如果你想支持旧版本,你需要检查 sys 模块的另一个版本属性)。

But you still need to take care of not using any Python language features in the file that are not available in older Python versions.但是您仍然需要注意不要在文件中使用旧 Python 版本中不可用的任何 Python 语言功能。 For example, this is allowed in Python 2.5 and later:例如,这在 Python 2.5 及更高版本中是允许的:

try:
    pass
except:
    pass
finally:
    pass

but won't work in older Python versions, because you could only have except OR finally match the try.但不适用于较旧的 Python 版本,因为您只能使用 except OR finally 匹配尝试。 So for compatibility with older Python versions you need to write:因此,为了与较旧的 Python 版本兼容,您需要编写:

try:
    try:
        pass
    except:
        pass
finally:
    pass

Several answers already suggest how to query the current python version.几个答案已经建议如何查询当前的 python 版本。 To check programmatically the version requirements, I'd make use of one of the following two methods:要以编程方式检查版本要求,我将使用以下两种方法之一:

# 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")

Just for fun, the following is a way of doing it on CPython 1.0-3.7b2, Pypy, Jython and Micropython.只是为了好玩,以下是在 CPython 1.0-3.7b2、Pypy、Jython 和 Micropython 上执行此操作的一种方式。 This is more of a curiosity than a way of doing it in modern code.这更像是一种好奇心,而不是现代代码中的一种方式。 I wrote it as part of http://stromberg.dnsalias.org/~strombrg/pythons/ , which is a script for testing a snippet of code on many versions of python at once, so you can easily get a feel for what python features are compatible with what versions of python:我把它写成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")

If you want to detect pre-Python 3 and don't want to import anything...如果您想检测 Python 3 之前的版本并且不想导入任何内容...

...you can (ab)use list comprehension scoping changes and do it in a single expression : ...您可以(ab)使用列表理解范围更改并在单个表达式中执行此操作:

is_python_3_or_above = (lambda x: [x for x in [False]] and None or x)(True)
from sys import version_info, api_version, version, hexversion

print(f"sys.version: {version}")
print(f"sys.api_version: {api_version}")
print(f"sys.version_info: {version_info}")
print(f"sys.hexversion: {hexversion}")

output输出

sys.version: 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] sys.api_version: 1013 sys.version_info: sys.version_info(major=3, minor=6, micro=5, releaselevel='final', serial=0) sys.hexversion: 50726384

The simplest way最简单的方法

Just type python in your terminal and you can see the version as like following只需在终端中输入 python ,您就可以看到如下所示的版本

desktop:~$ python
Python 2.7.6 (default, Jun 22 2015, 18:00:18) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 

sys.version_info doesn't seem to return a tuple as of 3.7. sys.version_info从 3.7 开始似乎没有返回tuple Rather, it returns a special class, so all of the examples using tuples don't work, for me at least.相反,它返回一个特殊的类,所以所有使用元组的例子都不起作用,至少对我来说。 Here's the output from a python console:这是 python 控制台的输出:

>>> import sys
>>> type(sys.version_info)
<class 'sys.version_info'>

I've found that using a combination of sys.version_info.major and sys.version_info.minor seems to suffice.我发现使用sys.version_info.majorsys.version_info.minor的组合似乎就足够了。 For example,...例如,...

import sys
if sys.version_info.major > 3:
    print('Upgrade to Python 3')
    exit(1)

checks if you're running Python 3. You can even check for more specific versions with...检查您是否正在运行 Python 3。您甚至可以使用...检查更具体的版本

import sys
ver = sys.version_info
if ver.major > 2:
    if ver.major == 3 and ver.minor <= 4:
        print('Upgrade to Python 3.5')
        exit(1)

can check to see if you're running at least Python 3.5.可以检查您是否至少在运行 Python 3.5。

Check Python version: python -V or python --version or apt-cache policy python检查 Python 版本: python -Vpython --versionapt-cache policy python

you can also run whereis python to see how many versions are installed.您还可以运行whereis python来查看安装了多少个版本。

To verify the Python version for commands on Windows, run the following commands in a command prompt and verify the output要在 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

Also, To see the folder configuration for each Python version, run the following commands:此外,要查看每个 Python 版本的文件夹配置,请运行以下命令:

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

The even simpler simplest way:更简单最简单的方法:

In Spyder, start a new "IPython Console", then run any of your existing scripts.在 Spyder 中,启动一个新的“IPython 控制台”,然后运行任何现有的脚本。

Now the version can be seen in the first output printed in the console window:现在可以在控制台窗口中打印的第一个输出中看到该版本:

"Python 3.7.3 (default, Apr 24 2019, 15:29:51)..." “Python 3.7.3(默认,2019 年 4 月 24 日,15:29:51)...”

在此处输入图像描述

To check from the command-line, in one single command, but include major, minor, micro version, releaselevel and serial , then invoke the same Python interpreter (ie same path) as you're using for your script:要从命令行检查,在一个命令中,但包括主要、次要、微版本、版本级别和串行,然后调用与您的脚本使用相同的 Python 解释器(即相同的路径):

> path/to/your/python -c "import sys; print('{}.{}.{}-{}-{}'.format(*sys.version_info))"

3.7.6-final-0

Note: .format() instead of f-strings or '.'.join() allows you to use arbitrary formatting and separator chars, eg to make this a greppable one-word string.注意: .format()而不是 f-strings 或'.'.join()允许您使用任意格式和分隔符字符,例如,使其成为一个 greppable 的单字字符串。 I put this inside a bash utility script that reports all important versions: python, numpy, pandas, sklearn, MacOS, xcode, clang, brew, conda, anaconda, gcc/g++ etc. Useful for logging, replicability, troubleshootingm bug-reporting etc.我把它放在一个 bash 实用程序脚本中,该脚本报告所有重要版本:python、numpy、pandas、sklearn、MacOS、xcode、clang、brew、conda、anaconda、gcc/g++ 等。对于日志记录、可复制性、故障排除、错误报告等很有用.

For windows, Go to command prompt and type this command to get the python version:对于 Windows,转到命令提示符并键入以下命令以获取 python 版本:

python --version

Or或者

python -V

From CMD type py --version Then press Enter key ad yo will see the python installed version like this Python 3.10.0从 CMD 输入py --version然后按 Enter 键,你会看到 python 安装的版本,像这样 Python 3.10.0

在此处输入图片说明

This just returns 2.7 , 3.6 or 3.9这只会返回2.73.63.9

import sys
current_version = ".".join(map(str, sys.version_info[0:2]))

which is what you usually you need...这是您通常需要的...

If you are working on linux just give command python output will be like this如果你在 linux 上工作,只需给出命令python输出将是这样的

Python 2.4.3 (#1, Jun 11 2009, 14:09:37) Python 2.4.3(#1,2009 年 6 月 11 日,14:09:37)

[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2 [GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] 在 linux2 上

Type "help", "copyright", "credits" or "license" for more information.输入“帮助”、“版权”、“信用”或“许可”以获取更多信息。

A attempt using os.popen to read it in a variable:尝试使用os.popen在变量中读取它:

import os
ver = os.popen('python -V').read().strip()
print(ver)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何知道 taskmgr 中正在运行哪个 python 脚本? - How do I know which python script is running in taskmgr? 如何检测我的 Python 脚本是否在“Windows 终端”中运行 - How do I detect if my Python script is running in the 'Windows Terminal' 检查运行给定脚本的 python 版本 - Check python version running a given script 如何检查我使用的是哪个版本的 NumPy? - How do I check which version of NumPy I'm using? 如何杀死正在运行的Python脚本? - How do I kill a running Python Script? 如何选择我在Linux上运行的python版本? - How to select which version of python I am running on Linux? 如何将具有特定文件扩展名的文件复制到我的python(2.5版)脚本中的文件夹中? - How do I copy files with specific file extension to a folder in my python (version 2.5) script? 如何在服务器上托管 function,我可以从我的 python 脚本调用它? - How do I host a function on a server, which I can call from my python script? 如何检查Python运行哪个Window Manager? - How can I check with Python which Window Manager is running? 使用python运行我的nlp脚本时,如何解决“名称&#39;score&#39;未定义”的问题? - How do I solve the problem of “name 'score' is not defined” when running my nlp script using python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM