标签归档:version

在运行时检查Python模块版本

问题:在运行时检查Python模块版本

许多第三方Python模块都有一个属性,该属性保存该模块的版本信息(通常是module.VERSIONmodule.__version__),但是有些则没有。

此类模块的特定示例是libxslt和libxml2。

我需要检查这些模块在运行时是否使用了正确的版本。有没有办法做到这一点?

潜在的解决方案是在运行时读取源代码,对其进行哈希处理,然后将其与已知版本的哈希进行比较,但这很讨厌。

有更好的解决方案吗?

Many third-party Python modules have an attribute which holds the version information for the module (usually something like module.VERSION or module.__version__), however some do not.

Particular examples of such modules are libxslt and libxml2.

I need to check that the correct version of these modules are being used at runtime. Is there a way to do this?

A potential solution wold be to read in the source at runtime, hash it, and then compare it to the hash of the known version, but that’s nasty.

Is there a better solutions?


回答 0

我会远离哈希。使用的libxslt版本可能包含某种补丁,但不会影响您的使用。

作为一种替代方法,我建议您不要在运行时检查(不知道这是否很困难)。对于我编写的具有外部依赖性(第3方库)的python东西,我编写了一个脚本,用户可以运行该脚本来检查其python安装,以查看是否安装了适当的模块版本。

对于没有定义的“版本”属性的模块,您可以检查其包含的接口(类和方法),并查看它们是否与期望的接口匹配。然后,在您正在使用的实际代码中,假设第3方模块具有您期望的接口。

I’d stay away from hashing. The version of libxslt being used might contain some type of patch that doesn’t effect your use of it.

As an alternative, I’d like to suggest that you don’t check at run time (don’t know if that’s a hard requirement or not). For the python stuff I write that has external dependencies (3rd party libraries), I write a script that users can run to check their python install to see if the appropriate versions of modules are installed.

For the modules that don’t have a defined ‘version’ attribute, you can inspect the interfaces it contains (classes and methods) and see if they match the interface they expect. Then in the actual code that you’re working on, assume that the 3rd party modules have the interface you expect.


回答 1

使用pkg_resources。从PyPI安装的所有内容至少应具有版本号。

>>> import pkg_resources
>>> pkg_resources.get_distribution("blogofile").version
'0.7.1'

Use pkg_resources. Anything installed from PyPI at least should have a version number.

>>> import pkg_resources
>>> pkg_resources.get_distribution("blogofile").version
'0.7.1'

回答 2

一些想法:

  1. 尝试检查所需版本中存在的功能或不存在的功能。
  2. 如果没有函数差异,请检查函数参数和签名。
  3. 如果无法从函数签名中找出问题,请在导入时设置一些存根调用并检查其行为。

Some ideas:

  1. Try checking for functions that exist or don’t exist in your needed versions.
  2. If there are no function differences, inspect function arguments and signatures.
  3. If you can’t figure it out from function signatures, set up some stub calls at import time and check their behavior.

回答 3

您可以使用

pip freeze

以需求格式查看已安装的软件包。

You can use

pip freeze

to see the installed packages in requirements format.


回答 4

您可以importlib_metadata为此使用库。

如果您使用的是python < 3.8,请首先使用以下命令进行安装:

pip install importlib_metadata

从python开始,3.8它就包含在python的标准库中。

然后,要检查软件包的版本(在本示例中为lxml),请运行:

>>> from importlib_metadata import version
>>> version('lxml')
'4.3.1'

请记住,这仅适用于从PyPI安装的软件包。同样,您必须将包名称作为version方法的参数传递,而不是此包提供的模块名称(尽管它们通常是相同的)。

If you’re on python >=3.8 you can use a module from the built-in library for that. To check a package’s version (in this example lxml) run:

>>> from importlib.metadata import version
>>> version('lxml')
'4.3.1'

This functionality has been ported to older versions of python (<3.8) as well, but you need to install a separate library first:

pip install importlib_metadata

and then to check a package’s version (in this example lxml) run:

>>> from importlib_metadata import version
>>> version('lxml')
'4.3.1'

Keep in mind that this works only for packages installed from PyPI. Also, you must pass a package name as an argument to the version method, rather than a module name that this package provides (although they’re usually the same).


回答 5

我发现使用各种可用的工具(包括此其他答案中pkg_resources提到的最好的一种)非常不可靠,因为它们中的大多数都不能涵盖所有情况。例如

  • 内置模块
  • 未安装但仅添加到python路径的模块(例如,通过您的IDE)
  • 可以使用同一模块的两个版本(在python路径中取代已安装的一个)

由于我们需要一种可靠的方法来获取任何软件包,模块或子模块的版本,因此我最终编写了getversion。使用起来非常简单:

from getversion import get_module_version
import foo
version, details = get_module_version(foo)

有关详细信息,请参见文档

I found it quite unreliable to use the various tools available (including the best one pkg_resources mentioned by this other answer), as most of them do not cover all cases. For example

  • built-in modules
  • modules not installed but just added to the python path (by your IDE for example)
  • two versions of the same module available (one in python path superseding the one installed)

Since we needed a reliable way to get the version of any package, module or submodule, I ended up writing getversion. It is quite simple to use:

from getversion import get_module_version
import foo
version, details = get_module_version(foo)

See the documentation for details.


回答 6

对于不提供__version__以下功能但可以使用的模块:

#!/usr/bin/env python3.6
import sys
import os
import subprocess
import re

sp = subprocess.run(["pip3", "show", "numpy"], stdout=subprocess.PIPE)
ver = sp.stdout.decode('utf-8').strip().split('\n')[1]
res = re.search('^Version:\ (.*)$', ver)
print(res.group(1))

要么

#!/usr/bin/env python3.7
import sys
import os
import subprocess
import re

sp = subprocess.run(["pip3", "show", "numpy"], capture_output=True)
ver = sp.stdout.decode('utf-8').strip().split('\n')[1]
res = re.search('^Version:\ (.*)$', ver)
print(res.group(1))

For modules which do not provide __version__ the following is ugly but works:

#!/usr/bin/env python3.6
import sys
import os
import subprocess
import re

sp = subprocess.run(["pip3", "show", "numpy"], stdout=subprocess.PIPE)
ver = sp.stdout.decode('utf-8').strip().split('\n')[1]
res = re.search('^Version:\ (.*)$', ver)
print(res.group(1))

or

#!/usr/bin/env python3.7
import sys
import os
import subprocess
import re

sp = subprocess.run(["pip3", "show", "numpy"], capture_output=True)
ver = sp.stdout.decode('utf-8').strip().split('\n')[1]
res = re.search('^Version:\ (.*)$', ver)
print(res.group(1))

在virtualenv中升级python

问题:在virtualenv中升级python

有没有一种方法可以升级virtualenv中使用的python版本(例如,如果出现错误修复版本)?

我可以pip freeze --local > requirements.txt删除目录和pip install -r requirements.txt,但这需要大量重新安装大型库,例如,numpy我经常使用。

我可以看到从2.6-> 2.7升级时这是一个优势,但是2.7.x-> 2.7.y呢?

Is there a way to upgrade the version of python used in a virtualenv (e.g. if a bugfix release comes out)?

I could pip freeze --local > requirements.txt, then remove the directory and pip install -r requirements.txt, but this requires a lot of reinstallation of large libraries, for instance, numpy, which I use a lot.

I can see this is an advantage when upgrading from, e.g., 2.6 -> 2.7, but what about 2.7.x -> 2.7.y?


回答 0

你看到吗?如果我没有误解这个答案,您可以尝试在旧版本的基础上创建一个新的virtualenv。您只需要知道哪个python将使用您的virtualenv(您将需要查看您的virtualenv版本)。

如果您的virtualenv安装了与旧版本相同的python版本,并且无法升级virtualenv软件包,则可能需要阅读此内容,以便使用所需的python版本安装virtualenv。

编辑

我已经测试了这种方法(在旧方法的基础上创建新的virtualenv的方法),它对我来说很好用。我认为,如果您从python 2.6更改为2.7或从2.7更改为3.x,则可能会遇到一些问题,但是如果您在同一版本内升级(保持在2.7不变),则不会有任何问题,因为所有软件包对于两个python版本,它们都位于相同的文件夹中(2.7.x和2.7.y软件包位于your_env / lib / python2.7 /中)。

如果更改了virtualenv python版本,则需要再次安装该版本的所有软件包(或仅将所需的软件包链接到新版本的packages文件夹中,即:your_env / lib / python_newversion / site-packages)

Did you see this? If I haven’t misunderstand that answer, you may try to create a new virtualenv on top of the old one. You just need to know which python is going to use your virtualenv (you will need to see your virtualenv version).

If your virtualenv is installed with the same python version of the old one and upgrading your virtualenv package is not an option, you may want to read this in order to install a virtualenv with the python version you want.

EDIT

I’ve tested this approach (the one that create a new virtualenv on top of the old one) and it worked fine for me. I think you may have some problems if you change from python 2.6 to 2.7 or 2.7 to 3.x but if you just upgrade inside the same version (staying at 2.7 as you want) you shouldn’t have any problem, as all the packages are held in the same folders for both python versions (2.7.x and 2.7.y packages are inside your_env/lib/python2.7/).

If you change your virtualenv python version, you will need to install all your packages again for that version (or just link the packages you need into the new version packages folder, i.e: your_env/lib/python_newversion/site-packages)


回答 1

如果您恰巧使用的是Python 3.3+随附的venv模块,则它支持一个--upgrade选项。根据文档

假设Python已就地升级,请升级环境目录以使用此版本的Python

python3 -m venv --upgrade ENV_DIR

If you happen to be using the venv module that comes with Python 3.3+, it supports an --upgrade option. Per the docs:

Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place

python3 -m venv --upgrade ENV_DIR

回答 2

再次更新: 以下方法在较新版本的virtualenv中可能不起作用。在尝试对旧版virtualenv进行修改之前,应将依赖项保存在需求文件(pip freeze > requirements.txt)中,并在其他位置进行备份。如果有任何问题,您仍然可以创建一个新的virtualenv并在其中安装旧的依赖项(pip install -r requirements.txt)。

更新:我最初回答5个月后就更改了答案。以下方法更方便,更可靠。

副作用:在将Python升级到v2.7.8之后在虚拟环境中Symbol not found: _SSLv2_method执行操作时,它还修复了异常import ssl

注意:目前,这仅适用于Python2.7.x


如果您在OS X上使用Homebrew Python,请首先使用deactivate所有virtualenv,然后升级Python:

brew update && brew upgrade python

运行以下命令(<EXISTING_ENV_PATH>是您的虚拟环境的路径):

cd <EXISTING_ENV_PATH>
rm .Python
rm bin/pip{,2,2.7}
rm bin/python{,2,2.7}
rm -r include/python2.7
rm lib/python2.7/*
rm -r lib/python2.7/distutils
rm lib/python2.7/site-packages/easy_install.*
rm -r lib/python2.7/site-packages/pip
rm -r lib/python2.7/site-packages/pip-*.dist-info
rm -r lib/python2.7/site-packages/setuptools
rm -r lib/python2.7/site-packages/setuptools-*.dist-info

最后,重新创建您的虚拟环境:

virtualenv <EXISTING_ENV_PATH>

这样一来,旧的Python核心文件和标准库(plus setuptoolspip)就被删除,而安装在其中的自定义库site-packages则在纯Python 中被保留并正常工作。二进制库可能需要也可能不需要重新安装才能正常运行。

这在安装了Django的5个虚拟环境中为我工作。

顺便说一句,如果./manage.py compilemessages之后仍然无法使用,请尝试以下操作:

brew install gettext && brew link gettext --force

Updated again: The following method might not work in newer versions of virtualenv. Before you try to make modifications to the old virtualenv, you should save the dependencies in a requirement file (pip freeze > requirements.txt) and make a backup of it somewhere else. If anything goes wrong, you can still create a new virtualenv and install the old dependencies in it (pip install -r requirements.txt).

Updated: I changed the answer 5 months after I originally answered. The following method is more convenient and robust.

Side effect: it also fixes the Symbol not found: _SSLv2_method exception when you do import ssl in a virtual environment after upgrading Python to v2.7.8.

Notice: Currently, this is for Python 2.7.x only.


If you’re using Homebrew Python on OS X, first deactivate all virtualenv, then upgrade Python:

brew update && brew upgrade python

Run the following commands (<EXISTING_ENV_PATH> is path of your virtual environment):

cd <EXISTING_ENV_PATH>
rm .Python
rm bin/pip{,2,2.7}
rm bin/python{,2,2.7}
rm -r include/python2.7
rm lib/python2.7/*
rm -r lib/python2.7/distutils
rm lib/python2.7/site-packages/easy_install.*
rm -r lib/python2.7/site-packages/pip
rm -r lib/python2.7/site-packages/pip-*.dist-info
rm -r lib/python2.7/site-packages/setuptools
rm -r lib/python2.7/site-packages/setuptools-*.dist-info

Finally, re-create your virtual environment:

virtualenv <EXISTING_ENV_PATH>

By doing so, old Python core files and standard libraries (plus setuptools and pip) are removed, while the custom libraries installed in site-packages are preserved and working, as soon as they are in pure Python. Binary libraries may or may not need to be reinstalled to function properly.

This worked for me on 5 virtual environments with Django installed.

BTW, if ./manage.py compilemessages is not working afterwards, try this:

brew install gettext && brew link gettext --force

回答 3

我无法在旧版本的基础上创建新的virtualenv。但是pip中有一些工具,可以更快地将需求重新安装到全新的venv中。Pip可以将requirements.txt中的每个项目构建到wheel包中,并将其存储在本地缓存中。当您创建新的venv并在其中运行pip install时,如果pip找到了它们,它将自动使用预建的轮子。车轮的安装速度比每个模块的setup.py运行速度快得多。

我的〜/ .pip / pip.conf看起来像这样:

[global]
download-cache = /Users/me/.pip/download-cache
find-links =
/Users/me/.pip/wheels/

[wheel]
wheel-dir = /Users/me/.pip/wheels

我安装了wheel(pip install wheel),然后运行pip wheel -r requirements.txt。这会将已构建的车轮存储在我的pip.conf中的wheel-dir中。

从那时起,每当我点安装这些要求中的任何一个时,它都会从轮子上安装它们,这非常快。

I wasn’t able to create a new virtualenv on top of the old one. But there are tools in pip which make it much faster to re-install requirements into a brand new venv. Pip can build each of the items in your requirements.txt into a wheel package, and store that in a local cache. When you create a new venv and run pip install in it, pip will automatically use the prebuilt wheels if it finds them. Wheels install much faster than running setup.py for each module.

My ~/.pip/pip.conf looks like this:

[global]
download-cache = /Users/me/.pip/download-cache
find-links =
/Users/me/.pip/wheels/

[wheel]
wheel-dir = /Users/me/.pip/wheels

I install wheel (pip install wheel), then run pip wheel -r requirements.txt. This stores the built wheels in the wheel-dir in my pip.conf.

From then on, any time I pip install any of these requirements, it installs them from the wheels, which is pretty quick.


回答 4

如何为现有的virtualenvwrapper项目升级Python版本并保持相同名称

我要为使用Doug Hellmann出色的virtualenvwrapper的任何人添加一个答案,特别是因为现有的答案对我没有帮助。

一些背景:

  • 我从事一些Python 2项目和Python 3项目;虽然我想使用python3 -m venv它,但它不支持Python 2环境
  • 当我开始一个新项目时,我使用mkproject它来创建虚拟环境,创建一个空项目目录,并在其中进行cds
  • 我想继续使用virtualenvwrapper的workon命令来激活任何项目,而与Python版本无关

方向:

假设您的现有项目已命名foo,并且当前正在运行Python 2(mkproject -p python2 foo),尽管从2.x升级到3.x,从3.6.0升级到3.6.1等的命令都是相同的。我还假设您当前位于激活的虚拟环境中。

1.停用并删除旧的虚拟环境:

$ deactivate
$ rmvirtualenv foo

请注意,如果您已将任何自定义命令添加到了挂钩(例如bin/postactivate),则需要在删除环境之前保存这些自定义命令。

2.将实际项目存储在temp目录中:

$ cd ..
$ mv foo foo-tmp

3.创建新的虚拟环境(和项目目录)并激活:

$ mkproject -p python3 foo

4.用实际项目替换生成的空项目目录,改回项目目录:

$ cd ..
$ mv -f foo-tmp foo
$ cdproject

5.重新安装依赖项,确认新的Python版本,等等:

$ pip install -r requirements.txt
$ python --version

如果这是一个常见的用例,我将考虑打开PR,为virtualenvwrapper 添加类似$ upgradevirtualenv/的内容$ upgradeproject

How to upgrade the Python version for an existing virtualenvwrapper project and keep the same name

I’m adding an answer for anyone using Doug Hellmann’s excellent virtualenvwrapper specifically since the existing answers didn’t do it for me.

Some context:

  • I work on some projects that are Python 2 and some that are Python 3; while I’d love to use python3 -m venv, it doesn’t support Python 2 environments
  • When I start a new project, I use mkproject which creates the virtual environment, creates an empty project directory, and cds into it
  • I want to continue using virtualenvwrapper’s workon command to activate any project irrespective of Python version

Directions:

Let’s say your existing project is named foo and is currently running Python 2 (mkproject -p python2 foo), though the commands are the same whether upgrading from 2.x to 3.x, 3.6.0 to 3.6.1, etc. I’m also assuming you’re currently inside the activated virtual environment.

1. Deactivate and remove the old virtual environment:

$ deactivate
$ rmvirtualenv foo

Note that if you’ve added any custom commands to the hooks (e.g., bin/postactivate) you’d need to save those before removing the environment.

2. Stash the real project in a temp directory:

$ cd ..
$ mv foo foo-tmp

3. Create the new virtual environment (and project dir) and activate:

$ mkproject -p python3 foo

4. Replace the empty generated project dir with real project, change back into project dir:

$ cd ..
$ mv -f foo-tmp foo
$ cdproject

5. Re-install dependencies, confirm new Python version, etc:

$ pip install -r requirements.txt
$ python --version

If this is a common use case, I’ll consider opening a PR to add something like $ upgradevirtualenv / $ upgradeproject to virtualenvwrapper.


回答 5

这种方法总是对我有用:

# First of all, delete all broken links. Replace  my_project_name` to your virtual env name
find ~/.virtualenvs/my_project_name/ -type l -delete
# Then create new links to the current Python version
virtualenv ~/.virtualenvs/my_project_name/
# It's it. Just repeat for each virtualenv located in ~/.virtualenvs

取自:

This approach always works for me:

# First of all, delete all broken links. Replace  my_project_name` to your virtual env name
find ~/.virtualenvs/my_project_name/ -type l -delete
# Then create new links to the current Python version
virtualenv ~/.virtualenvs/my_project_name/
# It's it. Just repeat for each virtualenv located in ~/.virtualenvs

Taken from:


回答 6

我将主目录从一台Mac移到了另一台(Mountain Lion到优胜美地),直到我失去了旧笔记本电脑的机会,才意识到虚拟机损坏了。brew自从Yosemite随附Python 2.7以来,我已经安装了指向Python 2.7的virtualenv点,因此我想将我的virtualenv更新为系统python。当我virtualenv在现有目录上运行时,OSError: [Errno 17] File exists: '/Users/hdara/bin/python2.7/lib/python2.7/config'出现错误。通过反复试验,我通过删除一些链接并手动修复了一些问题来解决此问题。这是我最终所做的(类似于@Rockalite所做的,但更简单):

cd <virtualenv-root>
rm lib/python2.7/config
rm lib/python2.7/lib-dynload
rm include/python2.7
rm .Python
cd lib/python2.7
gfind . -type l -xtype l | while read f; do ln -s -f /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/${f#./} $f; done

之后,我就可以在现有目录之上运行virtualenv了。

I moved my home directory from one mac to another (Mountain Lion to Yosemite) and didn’t realize about the broken virtualenv until I lost hold of the old laptop. I had the virtualenv point to Python 2.7 installed by brew and since Yosemite came with Python 2.7, I wanted to update my virtualenv to the system python. When I ran virtualenv on top of the existing directory, I was getting OSError: [Errno 17] File exists: '/Users/hdara/bin/python2.7/lib/python2.7/config' error. By trial and error, I worked around this issue by removing a few links and fixing up a few more manually. This is what I finally did (similar to what @Rockalite did, but simpler):

cd <virtualenv-root>
rm lib/python2.7/config
rm lib/python2.7/lib-dynload
rm include/python2.7
rm .Python
cd lib/python2.7
gfind . -type l -xtype l | while read f; do ln -s -f /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/${f#./} $f; done

After this, I was able to just run virtualenv on top of the existing directory.


回答 7

在使用Homebrew安装和升级Python3的OS X或macOS上,我必须先删除符号链接,然后python -m venv --upgrade ENV_DIR才能使用。

我将以下内容保存在upgrade_python3.sh中,所以我会记得从现在开始需要几个月的时间:

brew upgrade python3
find ~/.virtualenvs/ -type l -delete
find ~/.virtualenvs/ -type d -mindepth 1 -maxdepth 1 -exec python3 -m venv --upgrade "{}" \;

更新:虽然这乍看起来似乎很好,但是当我运行py.test时却出现了错误。最后,我只是从需求文件中重新创建了环境。

On OS X or macOS using Homebrew to install and upgrade Python3 I had to delete symbolic links before python -m venv --upgrade ENV_DIR would work.

I saved the following in upgrade_python3.sh so I would remember how months from now when I need to do it again:

brew upgrade python3
find ~/.virtualenvs/ -type l -delete
find ~/.virtualenvs/ -type d -mindepth 1 -maxdepth 1 -exec python3 -m venv --upgrade "{}" \;

UPDATE: while this seemed to work well at first, when I ran py.test it gave an error. In the end I just re-created the environment from a requirements file.


回答 8

如果您使用pipenv,我不知道是否可以在适当的位置升级环境,但是至少对于次要版本升级来说,它似乎足够聪明,在创建新环境时不从头开始重建软件包。例如,从3.6.4到3.6.5:

$ pipenv --python 3.6.5 install
Virtualenv already exists!
Removing existing virtualenv
Creating a v$ pipenv --python 3.6.5 install
Virtualenv already exists!
Removing existing virtualenv
Creating a virtualenv for this project
Using /usr/local/bin/python3.6m (3.6.5) to create virtualenv
Running virtualenv with interpreter /usr/local/bin/python3.6m
Using base prefix '/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/dmoles/.local/share/virtualenvs/autoscale-aBUhewiD/bin/python3.6
Also creating executable in /Users/dmoles/.local/share/virtualenvs/autoscale-aBUhewiD/bin/python
Installing setuptools, pip, wheel...done.

Virtualenv location: /Users/dmoles/.local/share/virtualenvs/autoscale-aBUhewiD
Installing dependencies from Pipfile.lock (84dd0e)…
  🐍   ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 47/47  00:00:24
To activate this project's virtualenv, run the following:
 $ pipenv shell
$ pipenv shell
Spawning environment shell (/bin/bash). Use 'exit' to leave.
. /Users/dmoles/.local/share/virtualenvs/autoscale-aBUhewiD/bin/activate
bash-3.2$ . /Users/dmoles/.local/share/virtualenvs/autoscale-aBUhewiD/bin/activate
(autoscale-aBUhewiD) bash-3.2$ python
Python 3.6.5 (default, Mar 30 2018, 06:41:53) 
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>>

If you’re using pipenv, I don’t know if it’s possible to upgrade an environment in place, but at least for minor version upgrades it seems to be smart enough not to rebuild packages from scratch when it creates a new environment. E.g., from 3.6.4 to 3.6.5:

$ pipenv --python 3.6.5 install
Virtualenv already exists!
Removing existing virtualenv…
Creating a v$ pipenv --python 3.6.5 install
Virtualenv already exists!
Removing existing virtualenv…
Creating a virtualenv for this project…
Using /usr/local/bin/python3.6m (3.6.5) to create virtualenv…
⠋Running virtualenv with interpreter /usr/local/bin/python3.6m
Using base prefix '/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/dmoles/.local/share/virtualenvs/autoscale-aBUhewiD/bin/python3.6
Also creating executable in /Users/dmoles/.local/share/virtualenvs/autoscale-aBUhewiD/bin/python
Installing setuptools, pip, wheel...done.

Virtualenv location: /Users/dmoles/.local/share/virtualenvs/autoscale-aBUhewiD
Installing dependencies from Pipfile.lock (84dd0e)…
  🐍   ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 47/47 — 00:00:24
To activate this project's virtualenv, run the following:
 $ pipenv shell
$ pipenv shell
Spawning environment shell (/bin/bash). Use 'exit' to leave.
. /Users/dmoles/.local/share/virtualenvs/autoscale-aBUhewiD/bin/activate
bash-3.2$ . /Users/dmoles/.local/share/virtualenvs/autoscale-aBUhewiD/bin/activate
(autoscale-aBUhewiD) bash-3.2$ python
Python 3.6.5 (default, Mar 30 2018, 06:41:53) 
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>>

回答 9

我只想澄清一下,因为有些答案是指venv,有些则是指virtualenv

在上支持使用-p--python标志virtualenv,但不支持venv。如果您有多个Python版本,并且想要指定使用哪个版本创建venv,请在命令行上执行以下操作:

malikarumi@Tetuoan2:~/Projects$ python3.6 -m venv {path to pre-existing dir you want venv in}

当然,您也可以venv像其他人指出的那样进行升级,但是前提是您已经升级了最初用于创建该Python的Python venv。您无法升级到系统上某个地方尚未拥有的Python版本,因此请确保首先获取所需的版本,然后再从中获取所需的所有Venv。

I just want to clarify, because some of the answers refer to venv and others refer to virtualenv.

Use of the -p or --python flag is supported on virtualenv, but not on venv. If you have more than one Python version and you want to specify which one to create the venv with, do it on the command line, like this:

malikarumi@Tetuoan2:~/Projects$ python3.6 -m venv {path to pre-existing dir you want venv in}

You can of course upgrade with venv as others have pointed out, but that assumes you have already upgraded the Python that was used to create that venv in the first place. You can’t upgrade to a Python version you don’t already have on your system somewhere, so make sure to get the version you want, first, then make all the venvs you want from it.


回答 10

步骤1:冻结要求并备份现有环境

pip freeze > requirements.txt
deactivate
mv env env_old

步骤2:安装Python 3.7并激活虚拟环境

sudo apt-get install python3.7-venv
python3.7 -m venv env
source env/bin/activate
python --version

步骤3:安装需求

sudo apt-get install python3.7-dev
pip3 install -r requirements.txt

Step 1: Freeze requirement & take a back-up of existing env

pip freeze > requirements.txt
deactivate
mv env env_old

Step 2: Install Python 3.7 & activate virutal environment

sudo apt-get install python3.7-venv
python3.7 -m venv env
source env/bin/activate
python --version

Step 3: Install requirements

sudo apt-get install python3.7-dev
pip3 install -r requirements.txt

回答 11

对于有问题的每个人

错误:命令'[‘/ Users / me / Sites / site / venv3 / bin / python3’,’-Im’,’ensurepip’,’-upgrade’,’-default-pip’]’返回非零退出状态1。

您必须安装python3.6-venv

 sudo apt-get install python3.6-venv

For everyone with the problem

Error: Command ‘[‘/Users/me/Sites/site/venv3/bin/python3’, ‘-Im’, ‘ensurepip’, ‘–upgrade’, ‘–default-pip’]’ returned non-zero exit status 1.

You have to install python3.6-venv

 sudo apt-get install python3.6-venv

如何在使用新语言功能的程序中检查Python版本?

问题:如何在使用新语言功能的程序中检查Python版本?

如果我有一个至少需要特定版本Python的Python脚本,那么使用较早版本的Python启动该脚本时,如何正确地正常失败是什么?

如何尽早获得控制权以发出错误消息并退出?

例如,我有一个使用ternery运算符(2.5中的新增功能)和“ with”块(2.6中的新增功能)的程序。我写了一个简单的解释程序版本检查程序,这是脚本会调用的第一件事……只是它没有那么远。相反,脚本在python编译期间失败,甚至没有调用我的例程。因此,脚本用户会看到一些非常模糊的synax错误回溯-这几乎需要专家来推断,这只是运行错误版本的Python的情况。

我知道如何检查Python版本。问题是某些语法在旧版本的Python中是非法的。考虑以下程序:

import sys
if sys.version_info < (2, 4):
    raise "must use python 2.5 or greater"
else:
    # syntax error in 2.4, ok in 2.5
    x = 1 if True else 2
    print x

在2.4下运行时,我想要这个结果

$ ~/bin/python2.4 tern.py 
must use python 2.5 or greater

而不是这个结果:

$ ~/bin/python2.4 tern.py 
  File "tern.py", line 5
    x = 1 if True else 2
           ^
SyntaxError: invalid syntax

(引导同事。)

If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script?

How do I get control early enough to issue an error message and exit?

For example, I have a program that uses the ternery operator (new in 2.5) and “with” blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call … except it doesn’t get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks – which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.

I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:

import sys
if sys.version_info < (2, 4):
    raise "must use python 2.5 or greater"
else:
    # syntax error in 2.4, ok in 2.5
    x = 1 if True else 2
    print x

When run under 2.4, I want this result

$ ~/bin/python2.4 tern.py 
must use python 2.5 or greater

and not this result:

$ ~/bin/python2.4 tern.py 
  File "tern.py", line 5
    x = 1 if True else 2
           ^
SyntaxError: invalid syntax

(Channeling for a coworker.)


回答 0

您可以使用进行测试eval

try:
  eval("1 if True else 2")
except SyntaxError:
  # doesn't have ternary

另外,with 可以在Python 2.5,只需添加from __future__ import with_statement

编辑:为了足够早地获得控制权,您可以将其拆分为不同的.py文件,并在导入之前检查主文件中的兼容性(例如,__init__.py在软件包中):

# __init__.py

# Check compatibility
try:
  eval("1 if True else 2")
except SyntaxError:
  raise ImportError("requires ternary support")

# import from another module
from impl import *

You can test using eval:

try:
  eval("1 if True else 2")
except SyntaxError:
  # doesn't have ternary

Also, with is available in Python 2.5, just add from __future__ import with_statement.

EDIT: to get control early enough, you could split it into different .py files and check compatibility in the main file before importing (e.g. in __init__.py in a package):

# __init__.py

# Check compatibility
try:
  eval("1 if True else 2")
except SyntaxError:
  raise ImportError("requires ternary support")

# import from another module
from impl import *

回答 1

围绕您的程序执行以下操作的包装器。

import sys

req_version = (2,5)
cur_version = sys.version_info

if cur_version >= req_version:
   import myApp
   myApp.run()
else:
   print "Your Python interpreter is too old. Please consider upgrading."

sys.version()如果您打算遇到使用2.0之前的Python解释器的人员,那么您也可以考虑使用,但是您需要做一些正则表达式。

并且可能会有更优雅的方法来做到这一点。

Have a wrapper around your program that does the following.

import sys

req_version = (2,5)
cur_version = sys.version_info

if cur_version >= req_version:
   import myApp
   myApp.run()
else:
   print "Your Python interpreter is too old. Please consider upgrading."

You can also consider using sys.version(), if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do.

And there might be more elegant ways to do this.


回答 2

尝试

导入平台
platform.python_version()

应该给你一个像“ 2.3.1”这样的字符串。如果这不完全符合您的要求,则可以通过“平台”内置的一组丰富的数据。您想要的东西应该在某个地方。

Try

import platform
platform.python_version()

Should give you a string like “2.3.1”. If this is not exactly waht you want there is a rich set of data available through the “platform” build-in. What you want should be in there somewhere.


回答 3

进行此版本比较的最佳方法可能是使用sys.hexversion。这很重要,因为比较版本元组不会在所有python版本中都提供所需的结果。

import sys
if sys.hexversion < 0x02060000:
    print "yep!"
else:
    print "oops!"

Probably the best way to do do this version comparison is to use the sys.hexversion. This is important because comparing version tuples will not give you the desired result in all python versions.

import sys
if sys.hexversion < 0x02060000:
    print "yep!"
else:
    print "oops!"

回答 4

import sys    
# prints whether python is version 3 or not
python_version = sys.version_info.major
if python_version == 3:
    print("is python 3")
else:
    print("not python 3")
import sys    
# prints whether python is version 3 or not
python_version = sys.version_info.major
if python_version == 3:
    print("is python 3")
else:
    print("not python 3")

回答 5

Nykakin在AskUbuntu的回答:

您还可以使用platform标准库中的模块从代码本身检查Python版本。

有两个功能:

  • platform.python_version() (返回字符串)。
  • platform.python_version_tuple() (返回元组)。

Python代码

创建例如文件:version.py

简单的版本检查方法:

import platform

print(platform.python_version())
print(platform.python_version_tuple())

您也可以使用以下eval方法:

try:
  eval("1 if True else 2")
except SyntaxError:
  raise ImportError("requires ternary support")

在命令行中运行Python文件:

$ python version.py 
2.7.11
('2', '7', '11')

Windows 10上的WAMP服务器通过CGI输出的Python输出:

屏幕截图2016-11-16 14.39.01通过Suriyaa Kudo


有用的资源

Answer from Nykakin at AskUbuntu:

You can also check Python version from code itself using platform module from standard library.

There are two functions:

  • platform.python_version() (returns string).
  • platform.python_version_tuple() (returns tuple).

The Python code

Create a file for example: version.py)

Easy method to check version:

import platform

print(platform.python_version())
print(platform.python_version_tuple())

You can also use the eval method:

try:
  eval("1 if True else 2")
except SyntaxError:
  raise ImportError("requires ternary support")

Run the Python file in a command line:

$ python version.py 
2.7.11
('2', '7', '11')

The output of Python with CGI via a WAMP Server on Windows 10:

Screenshot 2016-11-16 14.39.01 by Suriyaa Kudo


Helpful resources


回答 6

为了保持向后兼容,集成为Python 2.4核心语言的一部分。那时我做到了,这也将为您工作:

if sys.version_info < (2, 4):
    from sets import Set as set

Sets became part of the core language in Python 2.4, in order to stay backwards compatible. I did this back then, which will work for you as well:

if sys.version_info < (2, 4):
    from sets import Set as set

回答 7

尽管问题是: 如何尽早控制并发出错误消息并退出

我回答的问题是: 如何在启动应用程序之前尽早控制控件以发出错误消息

与其他帖子相比,我的回答有很大不同。到目前为止,似乎有答案正在尝试从Python内部解决您的问题。

我说,在启动Python之前先进行版本检查。我看到您的路径是Linux或UNIX。但是,我只能为您提供Windows脚本。我形象地将其适应Linux脚本语法并不难。

这是2.7版的DOS脚本:

@ECHO OFF
REM see http://ss64.com/nt/for_f.html
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
IF NOT ErrorLevel 1 GOTO Python27
ECHO must use python2.7 or greater
GOTO EOF
:Python27
python.exe tern.py
GOTO EOF
:EOF

这不会运行应用程序的任何部分,因此不会引发Python异常。它不会创建任何临时文件或添加任何OS环境变量。由于版本语法规则不同,它不会使您的应用程序异常终止。这是三个较少的安全访问点。

FOR /F线是关键。

FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul

对于多个python版本,请检查URL:http : //www.fpschultze.de/modules/smartfaq/faq.php? faqid =17

和我的hack版本:

[MS脚本;Python模块的Python版本检查预启动] http://pastebin.com/aAuJ91FQ

Although the question is: How do I get control early enough to issue an error message and exit?

The question that I answer is: How do I get control early enough to issue an error message before starting the app?

I can answer it a lot differently then the other posts. Seems answers so far are trying to solve your question from within Python.

I say, do version checking before launching Python. I see your path is Linux or unix. However I can only offer you a Windows script. I image adapting it to linux scripting syntax wouldn’t be too hard.

Here is the DOS script with version 2.7:

@ECHO OFF
REM see http://ss64.com/nt/for_f.html
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
IF NOT ErrorLevel 1 GOTO Python27
ECHO must use python2.7 or greater
GOTO EOF
:Python27
python.exe tern.py
GOTO EOF
:EOF

This does not run any part of your application and therefore will not raise a Python Exception. It does not create any temp file or add any OS environment variables. And it doesn’t end your app to an exception due to different version syntax rules. That’s three less possible security points of access.

The FOR /F line is the key.

FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul

For multiple python version check check out url: http://www.fpschultze.de/modules/smartfaq/faq.php?faqid=17

And my hack version:

[MS script; Python version check prelaunch of Python module] http://pastebin.com/aAuJ91FQ


回答 8

import sys
sys.version

将会得到这样的答案

‘2.7.6(默认值,2016年10月26日,20:30:19)\ n [GCC 4.8.4]’

这里2.7.6是版本

import sys
sys.version

will be getting answer like this

‘2.7.6 (default, Oct 26 2016, 20:30:19) \n[GCC 4.8.4]’

here 2.7.6 is version


回答 9

如上所述,语法错误发生在编译时,而不是运行时。虽然Python是一种“解释语言”,但实际上并没有直接解释Python代码。它被编译为字节码,然后被解释。导入模块时会发生一个编译步骤(如果没有可用的.pyc或.pyd文件形式的已编译版本),那就是您遇到错误的时候,而不是(完全正确)何时您的代码正在运行。

如上所述,您可以通过使用eval来推迟编译步骤,并使其在运行时针对单行代码发生,但是我个人更希望避免这样做,因为这可能导致Python潜在地执行不必要的运行时编译,一方面,另一方面,它使我感到代码混乱。(如果需要,您可以生成代码,再生成代码,然后再生成代码,并在从现在起的6个月内花费大量的时间进行修改和调试。)因此,我建议使用的是这样的内容:

import sys
if sys.hexversion < 0x02060000:
    from my_module_2_5 import thisFunc, thatFunc, theOtherFunc
else:
    from my_module import thisFunc, thatFunc, theOtherFunc

..即使我只有一个使用较新语法的函数也很短,我还是会这样做。(实际上,我将采取一切合理的措施来最大程度地减少此类函数的数量和大小。我什至可以编写其中只有那一行语法的类似ifTrueAElseB(cond,a,b)的函数。)

可能需要指出的另一件事(我还没有人指出,我感到有些惊讶)是,尽管Python的早期版本不支持类似

value = 'yes' if MyVarIsTrue else 'no'

..它确实支持如下代码

value = MyVarIsTrue and 'yes' or 'no'

那是三元表达式的写法。我尚未安装Python 3,但据我所知,这种“旧”方式至今仍然有效,因此您可以自行决定是否有条件地使用新语法是否值得支持使用旧版本的Python。

As noted above, syntax errors occur at compile time, not at run time. While Python is an “interpreted language”, Python code is not actually directly interpreted; it’s compiled to byte code, which is then interpreted. There is a compile step that happens when a module is imported (if there is no already-compiled version available in the form of a .pyc or .pyd file) and that’s when you’re getting your error, not (quite exactly) when your code is running.

You can put off the compile step and make it happen at run time for a single line of code, if you want to, by using eval, as noted above, but I personally prefer to avoid doing that, because it causes Python to perform potentially unnecessary run-time compilation, for one thing, and for another, it creates what to me feels like code clutter. (If you want, you can generate code that generates code that generates code – and have an absolutely fabulous time modifying and debugging that in 6 months from now.) So what I would recommend instead is something more like this:

import sys
if sys.hexversion < 0x02060000:
    from my_module_2_5 import thisFunc, thatFunc, theOtherFunc
else:
    from my_module import thisFunc, thatFunc, theOtherFunc

.. which I would do even if I only had one function that used newer syntax and it was very short. (In fact I would take every reasonable measure to minimize the number and size of such functions. I might even write a function like ifTrueAElseB(cond, a, b) with that single line of syntax in it.)

Another thing that might be worth pointing out (that I’m a little amazed no one has pointed out yet) is that while earlier versions of Python did not support code like

value = 'yes' if MyVarIsTrue else 'no'

..it did support code like

value = MyVarIsTrue and 'yes' or 'no'

That was the old way of writing ternary expressions. I don’t have Python 3 installed yet, but as far as I know, that “old” way still works to this day, so you can decide for yourself whether or not it’s worth it to conditionally use the new syntax, if you need to support the use of older versions of Python.


回答 10

将以下内容放在文件的最上方:

import sys

if float(sys.version.split()[0][:3]) < 2.7:
    print "Python 2.7 or higher required to run this code, " + sys.version.split()[0] + " detected, exiting."
    exit(1)

然后继续普通的Python代码:

import ...
import ...
other code...

Put the following at the very top of your file:

import sys

if float(sys.version.split()[0][:3]) < 2.7:
    print "Python 2.7 or higher required to run this code, " + sys.version.split()[0] + " detected, exiting."
    exit(1)

Then continue on with the normal Python code:

import ...
import ...
other code...

回答 11

我认为最好的方法是测试功能而不是版本。在某些情况下,这是微不足道的,而在其他情况下则并非如此。

例如:

try :
    # Do stuff
except : # Features weren't found.
    # Do stuff for older versions.

只要您对使用try / except块有足够的专业知识,就可以覆盖大多数基础知识。

I think the best way is to test for functionality rather than versions. In some cases, this is trivial, not so in others.

eg:

try :
    # Do stuff
except : # Features weren't found.
    # Do stuff for older versions.

As long as you’re specific in enough in using the try/except blocks, you can cover most of your bases.


回答 12

在尝试自己解决问题时,我经过快速搜索后才发现此问题,我根据上述一些建议提出了一种混合解决方案。

我喜欢DevPlayer使用包装器脚本的想法,但缺点是您最终要为不同的操作系统维护多个包装器,因此我决定用python编写包装器,但使用相同的基本“通过运行exe来获取版本”逻辑并提出了这一点。

我认为它应该适用于2.5及更高版本。到目前为止,我已经在Linux上的2.66、2.7.0和3.1.2以及OS X上的2.6.1上进行了测试。

import sys, subprocess
args = [sys.executable,"--version"]

output, error = subprocess.Popen(args ,stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()
print("The version is: '%s'"  %error.decode(sys.stdout.encoding).strip("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLMNBVCXZ,.+ \n") )

是的,我知道最后的解码/带状线很可怕,但是我只是想快速获取版本号。我将对此进行完善。

目前,这对于我来说已经足够好了,但是如果有人可以改进它(或者告诉我为什么这是一个糟糕的主意),那也很酷。

I just found this question after a quick search whilst trying to solve the problem myself and I’ve come up with a hybrid based on a few of the suggestions above.

I like DevPlayer’s idea of using a wrapper script, but the downside is that you end up maintaining multiple wrappers for different OSes, so I decided to write the wrapper in python, but use the same basic “grab the version by running the exe” logic and came up with this.

I think it should work for 2.5 and onwards. I’ve tested it on 2.66, 2.7.0 and 3.1.2 on Linux and 2.6.1 on OS X so far.

import sys, subprocess
args = [sys.executable,"--version"]

output, error = subprocess.Popen(args ,stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()
print("The version is: '%s'"  %error.decode(sys.stdout.encoding).strip("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLMNBVCXZ,.+ \n") )

Yes, I know the final decode/strip line is horrible, but I just wanted to quickly grab the version number. I’m going to refine that.

This works well enough for me for now, but if anyone can improve it (or tell me why it’s a terrible idea) that’d be cool too.


回答 13

对于 独立的 python脚本,以下用于强制执行python版本(此处为v2.7.x)的模块docstring技巧适用(在* nix上测试)。

#!/bin/sh
''''python -V 2>&1 | grep -q 2.7 && exec python -u -- "$0" ${1+"$@"}; echo "python 2.7.x missing"; exit 1 # '''

import sys
[...]

这也应该处理丢失的python可执行文件,但是对grep有依赖性。有关背景,请参见此处

For standalone python scripts, the following module docstring trick to enforce a python version (here v2.7.x) works (tested on *nix).

#!/bin/sh
''''python -V 2>&1 | grep -q 2.7 && exec python -u -- "$0" ${1+"$@"}; echo "python 2.7.x missing"; exit 1 # '''

import sys
[...]

This should handle missing python executable as well but has a dependency on grep. See here for background.


回答 14

您可以使用sys.hexversion或进行检查sys.version_info

sys.hexversion 不是很友好,因为它是一个十六进制数。 sys.version_info是一个元组,因此更加人性化。

使用以下命令检查Python 3.6或更高版本sys.hexversion

import sys, time
if sys.hexversion < 0x30600F0:
    print("You need Python 3.6 or greater.")
    for _ in range(1, 5): time.sleep(1)
    exit()

使用以下命令检查Python 3.6或更高版本sys.version_info

import sys, time
if sys.version_info[0] < 3 and sys.version_info[1] < 6:
    print("You need Python 3.6 or greater.")
    for _ in range(1, 5): time.sleep(1)
    exit()

sys.version_info更加人性化,但需要更多字符。我会推荐sys.hexversion,即使它不那么人性化。

希望对您有所帮助!

You can check with sys.hexversion or sys.version_info.

sys.hexversion isn’t very human-friendly because it’s a hexadecimal number. sys.version_info is a tuple, so it’s more human-friendly.

Check for Python 3.6 or newer with sys.hexversion:

import sys, time
if sys.hexversion < 0x30600F0:
    print("You need Python 3.6 or greater.")
    for _ in range(1, 5): time.sleep(1)
    exit()

Check for Python 3.6 or newer with sys.version_info:

import sys, time
if sys.version_info[0] < 3 and sys.version_info[1] < 6:
    print("You need Python 3.6 or greater.")
    for _ in range(1, 5): time.sleep(1)
    exit()

sys.version_info is more human-friendly, but takes more characters. I would reccomend sys.hexversion, even though it is less human-friendly.

I hope this helped you!


回答 15

我正在扩展akhan的出色答案,该答案甚至在Python脚本编译之前就打印出了有用的信息。

如果要确保该脚本正在使用Python 3.6或更高版本运行,请将这两行添加到Python脚本的顶部:

#!/bin/sh
''''python3 -c 'import sys; sys.exit(sys.version_info < (3, 6))' && exec python3 -u -- "$0" ${1+"$@"}; echo 'This script requires Python 3.6 or newer.'; exit 1 # '''

(注意:第二行以四个单引号开头,以三个单引号结尾单引号。这看起来很奇怪,但这不是一个错字。)

该解决方案的优势在于,如果使用的Python版本早于3.6,则print(f'Hello, {name}!')不会导致类似的代码SyntaxError。您会看到以下有用信息:

This script requires Python 3.6 or newer.

当然,该解决方案仅在类Unix的shell上有效,并且仅在脚本被直接调用(例如./script.py:)并且设置了适当的eXecute权限位时才有效。

I’m expanding on akhan’s excellent answer, which prints a helpful message before the Python script is even compiled.

If you want to ensure that the script is being run with Python 3.6 or newer, add these two lines to the top of your Python script:

#!/bin/sh
''''python3 -c 'import sys; sys.exit(sys.version_info < (3, 6))' && exec python3 -u -- "$0" ${1+"$@"}; echo 'This script requires Python 3.6 or newer.'; exit 1 # '''

(Note: The second line starts with four single-quotes and ends with three single-quotes. This may look strange, but it is not a typo.)

The advantage of this solution is that code like print(f'Hello, {name}!') won’t cause a SyntaxError if a Python version older than 3.6 is used. You’ll see this helpful message instead:

This script requires Python 3.6 or newer.

Of course, this solution only works on Unix-like shells, and only when the script is invoked directly (such as: ./script.py), and with the proper eXecute permission bits set.


回答 16

这个怎么样:

import sys

def testPyVer(reqver):
  if float(sys.version[:3]) >= reqver:
    return 1
  else:
    return 0

#blah blah blah, more code

if testPyVer(3.0) == 1:
  #do stuff
else:
  #print python requirement, exit statement

How about this:

import sys

def testPyVer(reqver):
  if float(sys.version[:3]) >= reqver:
    return 1
  else:
    return 0

#blah blah blah, more code

if testPyVer(3.0) == 1:
  #do stuff
else:
  #print python requirement, exit statement

回答 17

问题很简单。您检查了版本是否小于 2.4,不小于或等于。因此,如果Python版本是2.4,则它不少于2.4。您应该拥有的是:

    if sys.version_info **<=** (2, 4):

,不

    if sys.version_info < (2, 4):

The problem is quite simple. You checked if the version was less than 2.4, not less than or equal to. So if the Python version is 2.4, it’s not less than 2.4. What you should have had was:

    if sys.version_info **<=** (2, 4):

, not

    if sys.version_info < (2, 4):

如何比较Python中的版本号?

问题:如何比较Python中的版本号?

我正在走一个包含鸡蛋的目录,将这些鸡蛋添加到sys.path。如果目录中有相同.egg的两个版本,我只想添加最新的一个。

我有一个正则表达式r"^(?P<eggName>\w+)-(?P<eggVersion>[\d\.]+)-.+\.egg$可以从文件名中提取名称和版本。问题是比较版本号,它是一个类似的字符串2.3.1

由于我正在比较字符串,所以2在10之上排序,但这对于版本来说是不正确的。

>>> "2.3.1" > "10.1.1"
True

我可以进行一些拆分,解析,转换为int等操作,最终得到解决方法。但这是Python,而不是Java。有没有比较版本字符串的优雅方法?

I am walking a directory that contains eggs to add those eggs to the sys.path. If there are two versions of the same .egg in the directory, I want to add only the latest one.

I have a regular expression r"^(?P<eggName>\w+)-(?P<eggVersion>[\d\.]+)-.+\.egg$ to extract the name and version from the filename. The problem is comparing the version number, which is a string like 2.3.1.

Since I’m comparing strings, 2 sorts above 10, but that’s not correct for versions.

>>> "2.3.1" > "10.1.1"
True

I could do some splitting, parsing, casting to int, etc., and I would eventually get a workaround. But this is Python, not Java. Is there an elegant way to compare version strings?


回答 0

使用packaging.version.parse

>>> from packaging import version
>>> version.parse("2.3.1") < version.parse("10.1.2")
True
>>> version.parse("1.3.a4") < version.parse("10.1.2")
True
>>> isinstance(version.parse("1.3.a4"), version.Version)
True
>>> isinstance(version.parse("1.3.xy123"), version.LegacyVersion)
True
>>> version.Version("1.3.xy123")
Traceback (most recent call last):
...
packaging.version.InvalidVersion: Invalid version: '1.3.xy123'

packaging.version.parse是第三方实用程序,但是由setuptools使用(因此您可能已经安装了它)并且符合当前的PEP 440packaging.version.Version如果版本兼容,则返回,否则返回packaging.version.LegacyVersion。后者将始终在有效版本之前排序。

注意:包装最近已出售给setuptools


distutils.version内置了许多软件仍在使用的一种古老的替代方案,它是内置的,但没有文件记载,仅与被取代的PEP 386相符 ;

>>> from distutils.version import LooseVersion, StrictVersion
>>> LooseVersion("2.3.1") < LooseVersion("10.1.2")
True
>>> StrictVersion("2.3.1") < StrictVersion("10.1.2")
True
>>> StrictVersion("1.3.a4")
Traceback (most recent call last):
...
ValueError: invalid version number '1.3.a4'

如您所见,它将有效的PEP 440版本视为“不严格”,因此与现代Python的有效版本概念不符。

正如distutils.version未记录的,这里是相关的文档字符串。

Use packaging.version.parse.

>>> from packaging import version
>>> version.parse("2.3.1") < version.parse("10.1.2")
True
>>> version.parse("1.3.a4") < version.parse("10.1.2")
True
>>> isinstance(version.parse("1.3.a4"), version.Version)
True
>>> isinstance(version.parse("1.3.xy123"), version.LegacyVersion)
True
>>> version.Version("1.3.xy123")
Traceback (most recent call last):
...
packaging.version.InvalidVersion: Invalid version: '1.3.xy123'

packaging.version.parse is a third-party utility but is used by setuptools (so you probably already have it installed) and is conformant to the current PEP 440; it will return a packaging.version.Version if the version is compliant and a packaging.version.LegacyVersion if not. The latter will always sort before valid versions.

Note: packaging has recently been vendored into setuptools.


An ancient alternative still used by a lot of software is distutils.version, built in but undocumented and conformant only to the superseded PEP 386;

>>> from distutils.version import LooseVersion, StrictVersion
>>> LooseVersion("2.3.1") < LooseVersion("10.1.2")
True
>>> StrictVersion("2.3.1") < StrictVersion("10.1.2")
True
>>> StrictVersion("1.3.a4")
Traceback (most recent call last):
...
ValueError: invalid version number '1.3.a4'

As you can see it sees valid PEP 440 versions as “not strict” and therefore doesn’t match modern Python’s notion of what a valid version is.

As distutils.version is undocumented, here‘s the relevant docstrings.


回答 1

包装库包含水电费与版本工作和其他包装相关的功能。这实现了PEP 0440-版本标识,并且还能够解析不遵循PEP的版本。pip和其他常见的Python工具使用它来提供版本解析和比较。

$ pip install packaging
from packaging.version import parse as parse_version
version = parse_version('1.0.3.dev')

这与setuptools和pkg_resources中的原始代码分开,以提供更轻便,更快速的程序包。


在打包库存在之前,可以(并且仍然可以)在pkg_resources(setuptools提供的软件包)中找到此功能。但是,由于不再保证已安装setuptools(存在其他打包工具),因此不再是首选方法,并且pkg_resources具有讽刺意味的是,在导入时会使用大量资源。但是,所有文档和讨论仍然相关。

parse_version()文档

解析PEP 440定义的项目的版本字符串。返回的值将是代表版本的对象。这些对象可以相互比较并排序。排序算法是由PEP 440定义的,此外,不是有效PEP 440版本的任何版本都将被视为小于任何有效PEP 440版本,并且无效版本将继续使用原始算法进行排序。

在PEP 440存在之前,所引用的“原始算法”是在文档的较早版本中定义的。

在语义上,格式是distutils StrictVersionLooseVersion类之间的粗略交叉。如果您提供适用于的版本StrictVersion,则它们将以相同的方式进行比较。否则,比较更像是“更智能”的形式LooseVersion。可以创建会使该解析器傻瓜的病理版本编码方案,但是在实践中它们应该很少见。

文档提供了一些示例:

如果要确定所选的编号方案可以按您认为的方式工作,则可以使用该pkg_resources.parse_version() 功能比较不同的版本号:

>>> from pkg_resources import parse_version
>>> parse_version('1.9.a.dev') == parse_version('1.9a0dev')
True
>>> parse_version('2.1-rc2') < parse_version('2.1')
True
>>> parse_version('0.6a9dev-r41475') < parse_version('0.6a9')
True

The packaging library contains utilities for working with versions and other packaging-related functionality. This implements PEP 0440 — Version Identification and is also able to parse versions that don’t follow the PEP. It is used by pip, and other common Python tools to provide version parsing and comparison.

$ pip install packaging
from packaging.version import parse as parse_version
version = parse_version('1.0.3.dev')

This was split off from the original code in setuptools and pkg_resources to provide a more lightweight and faster package.


Before the packaging library existed, this functionality was (and can still be) found in pkg_resources, a package provided by setuptools. However, this is no longer preferred as setuptools is no longer guaranteed to be installed (other packaging tools exist), and pkg_resources ironically uses quite a lot of resources when imported. However, all the docs and discussion are still relevant.

From the parse_version() docs:

Parsed a project’s version string as defined by PEP 440. The returned value will be an object that represents the version. These objects may be compared to each other and sorted. The sorting algorithm is as defined by PEP 440 with the addition that any version which is not a valid PEP 440 version will be considered less than any valid PEP 440 version and the invalid versions will continue sorting using the original algorithm.

The “original algorithm” referenced was defined in older versions of the docs, before PEP 440 existed.

Semantically, the format is a rough cross between distutils’ StrictVersion and LooseVersion classes; if you give it versions that would work with StrictVersion, then they will compare the same way. Otherwise, comparisons are more like a “smarter” form of LooseVersion. It is possible to create pathological version coding schemes that will fool this parser, but they should be very rare in practice.

The documentation provides some examples:

If you want to be certain that your chosen numbering scheme works the way you think it will, you can use the pkg_resources.parse_version() function to compare different version numbers:

>>> from pkg_resources import parse_version
>>> parse_version('1.9.a.dev') == parse_version('1.9a0dev')
True
>>> parse_version('2.1-rc2') < parse_version('2.1')
True
>>> parse_version('0.6a9dev-r41475') < parse_version('0.6a9')
True

回答 2

def versiontuple(v):
    return tuple(map(int, (v.split("."))))

>>> versiontuple("2.3.1") > versiontuple("10.1.1")
False
def versiontuple(v):
    return tuple(map(int, (v.split("."))))

>>> versiontuple("2.3.1") > versiontuple("10.1.1")
False

回答 3

将版本字符串转换为元组然后从那里去怎么办?对我来说似乎足够优雅

>>> (2,3,1) < (10,1,1)
True
>>> (2,3,1) < (10,1,1,1)
True
>>> (2,3,1,10) < (10,1,1,1)
True
>>> (10,3,1,10) < (10,1,1,1)
False
>>> (10,3,1,10) < (10,4,1,1)
True

@kindall的解决方案是一个很好的代码示例。

What’s wrong with transforming the version string into a tuple and going from there? Seems elegant enough for me

>>> (2,3,1) < (10,1,1)
True
>>> (2,3,1) < (10,1,1,1)
True
>>> (2,3,1,10) < (10,1,1,1)
True
>>> (10,3,1,10) < (10,1,1,1)
False
>>> (10,3,1,10) < (10,4,1,1)
True

@kindall’s solution is a quick example of how good the code would look.


回答 4

有可用的打包程序包,使您可以比较PEP-440的版本以及旧版。

>>> from packaging.version import Version, LegacyVersion
>>> Version('1.1') < Version('1.2')
True
>>> Version('1.2.dev4+deadbeef') < Version('1.2')
True
>>> Version('1.2.8.5') <= Version('1.2')
False
>>> Version('1.2.8.5') <= Version('1.2.8.6')
True

旧版支持:

>>> LegacyVersion('1.2.8.5-5-gdeadbeef')
<LegacyVersion('1.2.8.5-5-gdeadbeef')>

将旧版本与PEP-440版本进行比较。

>>> LegacyVersion('1.2.8.5-5-gdeadbeef') < Version('1.2.8.6')
True

There is packaging package available, which will allow you to compare versions as per PEP-440, as well as legacy versions.

>>> from packaging.version import Version, LegacyVersion
>>> Version('1.1') < Version('1.2')
True
>>> Version('1.2.dev4+deadbeef') < Version('1.2')
True
>>> Version('1.2.8.5') <= Version('1.2')
False
>>> Version('1.2.8.5') <= Version('1.2.8.6')
True

Legacy version support:

>>> LegacyVersion('1.2.8.5-5-gdeadbeef')
<LegacyVersion('1.2.8.5-5-gdeadbeef')>

Comparing legacy version with PEP-440 version.

>>> LegacyVersion('1.2.8.5-5-gdeadbeef') < Version('1.2.8.6')
True

回答 5

您可以使用semver包来确定版本是否满足语义版本要求。这与比较两个实际版本不同,只是一种比较。

例如,版本3.6.0 + 1234应该与3.6.0相同。

import semver
semver.match('3.6.0+1234', '==3.6.0')
# True

from packaging import version
version.parse('3.6.0+1234') == version.parse('3.6.0')
# False

from distutils.version import LooseVersion
LooseVersion('3.6.0+1234') == LooseVersion('3.6.0')
# False

You can use the semver package to determine if a version satisfies a semantic version requirement. This is not the same as comparing two actual versions, but is a type of comparison.

For example, version 3.6.0+1234 should be the same as 3.6.0.

import semver
semver.match('3.6.0+1234', '==3.6.0')
# True

from packaging import version
version.parse('3.6.0+1234') == version.parse('3.6.0')
# False

from distutils.version import LooseVersion
LooseVersion('3.6.0+1234') == LooseVersion('3.6.0')
# False

回答 6

根据Kindall的解决方案发布我的全部功能。通过用前导零填充每个版本部分,我能够支持与数字混合的任何字母数字字符。

尽管肯定不如他的一线功能,但它似乎可以与字母数字版本号一起很好地工作。(zfill(#)如果版本控制系统中包含长字符串,请确保正确设置该值。)

def versiontuple(v):
   filled = []
   for point in v.split("."):
      filled.append(point.zfill(8))
   return tuple(filled)

>>> versiontuple("10a.4.5.23-alpha") > versiontuple("2a.4.5.23-alpha")
True


>>> "10a.4.5.23-alpha" > "2a.4.5.23-alpha"
False

Posting my full function based on Kindall’s solution. I was able to support any alphanumeric characters mixed in with the numbers by padding each version section with leading zeros.

While certainly not as pretty as his one-liner function, it seems to work well with alpha-numeric version numbers. (Just be sure to set the zfill(#) value appropriately if you have long strings in your versioning system.)

def versiontuple(v):
   filled = []
   for point in v.split("."):
      filled.append(point.zfill(8))
   return tuple(filled)

.

>>> versiontuple("10a.4.5.23-alpha") > versiontuple("2a.4.5.23-alpha")
True


>>> "10a.4.5.23-alpha" > "2a.4.5.23-alpha"
False

回答 7

这件事的方法setuptools做它,它使用的pkg_resources.parse_version功能。它应该符合PEP440

例:

#! /usr/bin/python
# -*- coding: utf-8 -*-
"""Example comparing two PEP440 formatted versions
"""
import pkg_resources

VERSION_A = pkg_resources.parse_version("1.0.1-beta.1")
VERSION_B = pkg_resources.parse_version("v2.67-rc")
VERSION_C = pkg_resources.parse_version("2.67rc")
VERSION_D = pkg_resources.parse_version("2.67rc1")
VERSION_E = pkg_resources.parse_version("1.0.0")

print(VERSION_A)
print(VERSION_B)
print(VERSION_C)
print(VERSION_D)

print(VERSION_A==VERSION_B) #FALSE
print(VERSION_B==VERSION_C) #TRUE
print(VERSION_C==VERSION_D) #FALSE
print(VERSION_A==VERSION_E) #FALSE

The way that setuptools does it, it uses the pkg_resources.parse_version function. It should be PEP440 compliant.

Example:

#! /usr/bin/python
# -*- coding: utf-8 -*-
"""Example comparing two PEP440 formatted versions
"""
import pkg_resources

VERSION_A = pkg_resources.parse_version("1.0.1-beta.1")
VERSION_B = pkg_resources.parse_version("v2.67-rc")
VERSION_C = pkg_resources.parse_version("2.67rc")
VERSION_D = pkg_resources.parse_version("2.67rc1")
VERSION_E = pkg_resources.parse_version("1.0.0")

print(VERSION_A)
print(VERSION_B)
print(VERSION_C)
print(VERSION_D)

print(VERSION_A==VERSION_B) #FALSE
print(VERSION_B==VERSION_C) #TRUE
print(VERSION_C==VERSION_D) #FALSE
print(VERSION_A==VERSION_E) #FALSE

回答 8

我一直在寻找不会添加任何新依赖项的解决方案。查看以下(Python 3)解决方案:

class VersionManager:

    @staticmethod
    def compare_version_tuples(
            major_a, minor_a, bugfix_a,
            major_b, minor_b, bugfix_b,
    ):

        """
        Compare two versions a and b, each consisting of 3 integers
        (compare these as tuples)

        version_a: major_a, minor_a, bugfix_a
        version_b: major_b, minor_b, bugfix_b

        :param major_a: first part of a
        :param minor_a: second part of a
        :param bugfix_a: third part of a

        :param major_b: first part of b
        :param minor_b: second part of b
        :param bugfix_b: third part of b

        :return:    1 if a  > b
                    0 if a == b
                   -1 if a  < b
        """
        tuple_a = major_a, minor_a, bugfix_a
        tuple_b = major_b, minor_b, bugfix_b
        if tuple_a > tuple_b:
            return 1
        if tuple_b > tuple_a:
            return -1
        return 0

    @staticmethod
    def compare_version_integers(
            major_a, minor_a, bugfix_a,
            major_b, minor_b, bugfix_b,
    ):
        """
        Compare two versions a and b, each consisting of 3 integers
        (compare these as integers)

        version_a: major_a, minor_a, bugfix_a
        version_b: major_b, minor_b, bugfix_b

        :param major_a: first part of a
        :param minor_a: second part of a
        :param bugfix_a: third part of a

        :param major_b: first part of b
        :param minor_b: second part of b
        :param bugfix_b: third part of b

        :return:    1 if a  > b
                    0 if a == b
                   -1 if a  < b
        """
        # --
        if major_a > major_b:
            return 1
        if major_b > major_a:
            return -1
        # --
        if minor_a > minor_b:
            return 1
        if minor_b > minor_a:
            return -1
        # --
        if bugfix_a > bugfix_b:
            return 1
        if bugfix_b > bugfix_a:
            return -1
        # --
        return 0

    @staticmethod
    def test_compare_versions():
        functions = [
            (VersionManager.compare_version_tuples, "VersionManager.compare_version_tuples"),
            (VersionManager.compare_version_integers, "VersionManager.compare_version_integers"),
        ]
        data = [
            # expected result, version a, version b
            (1, 1, 0, 0, 0, 0, 1),
            (1, 1, 5, 5, 0, 5, 5),
            (1, 1, 0, 5, 0, 0, 5),
            (1, 0, 2, 0, 0, 1, 1),
            (1, 2, 0, 0, 1, 1, 0),
            (0, 0, 0, 0, 0, 0, 0),
            (0, -1, -1, -1, -1, -1, -1),  # works even with negative version numbers :)
            (0, 2, 2, 2, 2, 2, 2),
            (-1, 5, 5, 0, 6, 5, 0),
            (-1, 5, 5, 0, 5, 9, 0),
            (-1, 5, 5, 5, 5, 5, 6),
            (-1, 2, 5, 7, 2, 5, 8),
        ]
        count = len(data)
        index = 1
        for expected_result, major_a, minor_a, bugfix_a, major_b, minor_b, bugfix_b in data:
            for function_callback, function_name in functions:
                actual_result = function_callback(
                    major_a=major_a, minor_a=minor_a, bugfix_a=bugfix_a,
                    major_b=major_b, minor_b=minor_b, bugfix_b=bugfix_b,
                )
                outcome = expected_result == actual_result
                message = "{}/{}: {}: {}: a={}.{}.{} b={}.{}.{} expected={} actual={}".format(
                    index, count,
                    "ok" if outcome is True else "fail",
                    function_name,
                    major_a, minor_a, bugfix_a,
                    major_b, minor_b, bugfix_b,
                    expected_result, actual_result
                )
                print(message)
                assert outcome is True
                index += 1
        # test passed!


if __name__ == '__main__':
    VersionManager.test_compare_versions()

编辑:添加了元组比较的变体。当然,具有元组比较的变体更好,但是我一直在寻找具有整数比较的变体

I was looking for a solution which wouldn’t add any new dependencies. Check out the following (Python 3) solution:

class VersionManager:

    @staticmethod
    def compare_version_tuples(
            major_a, minor_a, bugfix_a,
            major_b, minor_b, bugfix_b,
    ):

        """
        Compare two versions a and b, each consisting of 3 integers
        (compare these as tuples)

        version_a: major_a, minor_a, bugfix_a
        version_b: major_b, minor_b, bugfix_b

        :param major_a: first part of a
        :param minor_a: second part of a
        :param bugfix_a: third part of a

        :param major_b: first part of b
        :param minor_b: second part of b
        :param bugfix_b: third part of b

        :return:    1 if a  > b
                    0 if a == b
                   -1 if a  < b
        """
        tuple_a = major_a, minor_a, bugfix_a
        tuple_b = major_b, minor_b, bugfix_b
        if tuple_a > tuple_b:
            return 1
        if tuple_b > tuple_a:
            return -1
        return 0

    @staticmethod
    def compare_version_integers(
            major_a, minor_a, bugfix_a,
            major_b, minor_b, bugfix_b,
    ):
        """
        Compare two versions a and b, each consisting of 3 integers
        (compare these as integers)

        version_a: major_a, minor_a, bugfix_a
        version_b: major_b, minor_b, bugfix_b

        :param major_a: first part of a
        :param minor_a: second part of a
        :param bugfix_a: third part of a

        :param major_b: first part of b
        :param minor_b: second part of b
        :param bugfix_b: third part of b

        :return:    1 if a  > b
                    0 if a == b
                   -1 if a  < b
        """
        # --
        if major_a > major_b:
            return 1
        if major_b > major_a:
            return -1
        # --
        if minor_a > minor_b:
            return 1
        if minor_b > minor_a:
            return -1
        # --
        if bugfix_a > bugfix_b:
            return 1
        if bugfix_b > bugfix_a:
            return -1
        # --
        return 0

    @staticmethod
    def test_compare_versions():
        functions = [
            (VersionManager.compare_version_tuples, "VersionManager.compare_version_tuples"),
            (VersionManager.compare_version_integers, "VersionManager.compare_version_integers"),
        ]
        data = [
            # expected result, version a, version b
            (1, 1, 0, 0, 0, 0, 1),
            (1, 1, 5, 5, 0, 5, 5),
            (1, 1, 0, 5, 0, 0, 5),
            (1, 0, 2, 0, 0, 1, 1),
            (1, 2, 0, 0, 1, 1, 0),
            (0, 0, 0, 0, 0, 0, 0),
            (0, -1, -1, -1, -1, -1, -1),  # works even with negative version numbers :)
            (0, 2, 2, 2, 2, 2, 2),
            (-1, 5, 5, 0, 6, 5, 0),
            (-1, 5, 5, 0, 5, 9, 0),
            (-1, 5, 5, 5, 5, 5, 6),
            (-1, 2, 5, 7, 2, 5, 8),
        ]
        count = len(data)
        index = 1
        for expected_result, major_a, minor_a, bugfix_a, major_b, minor_b, bugfix_b in data:
            for function_callback, function_name in functions:
                actual_result = function_callback(
                    major_a=major_a, minor_a=minor_a, bugfix_a=bugfix_a,
                    major_b=major_b, minor_b=minor_b, bugfix_b=bugfix_b,
                )
                outcome = expected_result == actual_result
                message = "{}/{}: {}: {}: a={}.{}.{} b={}.{}.{} expected={} actual={}".format(
                    index, count,
                    "ok" if outcome is True else "fail",
                    function_name,
                    major_a, minor_a, bugfix_a,
                    major_b, minor_b, bugfix_b,
                    expected_result, actual_result
                )
                print(message)
                assert outcome is True
                index += 1
        # test passed!


if __name__ == '__main__':
    VersionManager.test_compare_versions()

EDIT: added variant with tuple comparison. Of course the variant with tuple comparison is nicer, but I was looking for the variant with integer comparison


如何查看我使用的NumPy版本?

问题:如何查看我使用的NumPy版本?

如何查看我使用的NumPy版本?

(仅供参考,此问题已被编辑,因为问题和答案都不是特定于平台的。)

How can I check which version of NumPy I’m using?

(FYI this question has been edited because both the question and answer are not platform specific.)


回答 0

import numpy
numpy.version.version
import numpy
numpy.version.version

回答 1

>> import numpy
>> print numpy.__version__
>> import numpy
>> print numpy.__version__

回答 2

从命令行,您可以简单地发出:

python -c "import numpy; print(numpy.version.version)"

要么:

python -c "import numpy; print(numpy.__version__)"

From the command line, you can simply issue:

python -c "import numpy; print(numpy.version.version)"

Or:

python -c "import numpy; print(numpy.__version__)"

回答 3

跑:

pip list

应生成软件包列表。滚动到numpy。

...
nbpresent (3.0.2)
networkx (1.11)
nltk (3.2.2)
nose (1.3.7)
notebook (5.0.0)
numba (0.32.0+0.g139e4c6.dirty)
numexpr (2.6.2)
numpy (1.11.3) <--
numpydoc (0.6.0)
odo (0.5.0)
openpyxl (2.4.1)
pandas (0.20.1)
pandocfilters (1.4.1)
....

Run:

pip list

Should generate a list of packages. Scroll through to numpy.

...
nbpresent (3.0.2)
networkx (1.11)
nltk (3.2.2)
nose (1.3.7)
notebook (5.0.0)
numba (0.32.0+0.g139e4c6.dirty)
numexpr (2.6.2)
numpy (1.11.3) <--
numpydoc (0.6.0)
odo (0.5.0)
openpyxl (2.4.1)
pandas (0.20.1)
pandocfilters (1.4.1)
....

回答 4

您还可以通过以下方式检查您的版本是否在使用MKL:

import numpy
numpy.show_config()

You can also check if your version is using MKL with:

import numpy
numpy.show_config()

回答 5

我们可以pip freeze用来获取任何Python软件包版本,而无需打开Python shell。

pip freeze | grep 'numpy'

We can use pip freeze to get any Python package version without opening the Python shell.

pip freeze | grep 'numpy'

回答 6

如果您正在使用Anaconda发行版中的NumPy,则可以执行以下操作:

$ conda list | grep numpy
numpy     1.11.3     py35_0

这也给出了Python版本。


如果您想要一些花哨的东西,请使用 numexpr

它提供了很多信息,如下所示:

In [692]: import numexpr

In [693]: numexpr.print_versions()
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Numexpr version:   2.6.2
NumPy version:     1.13.3
Python version:    3.6.3 |Anaconda custom (64-bit)|
                   (default, Oct 13 2017, 12:02:49)
[GCC 7.2.0]
Platform:          linux-x86_64
AMD/Intel CPU?     True
VML available?     False
Number of threads used by default: 8 (out of 48 detected cores)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

If you’re using NumPy from the Anaconda distribution, then you can just do:

$ conda list | grep numpy
numpy     1.11.3     py35_0

This gives the Python version as well.


If you want something fancy, then use numexpr

It gives lot of information as you can see below:

In [692]: import numexpr

In [693]: numexpr.print_versions()
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Numexpr version:   2.6.2
NumPy version:     1.13.3
Python version:    3.6.3 |Anaconda custom (64-bit)|
                   (default, Oct 13 2017, 12:02:49)
[GCC 7.2.0]
Platform:          linux-x86_64
AMD/Intel CPU?     True
VML available?     False
Number of threads used by default: 8 (out of 48 detected cores)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

回答 7

您可以尝试以下方法:

点显示numpy

You can try this:

pip show numpy


回答 8

您可以使用Terminal或Python代码获取numpy版本。

在使用Ubuntu的终端机(bash)中:

pip list | grep numpy

在python 3.6.7中,此代码显示了numpy版本:

import numpy
print (numpy.version.version)

如果将此代码插入到showumpy.py文件中,则可以对其进行编译:

python shownumpy.py

要么

python3 shownumpy.py

我有以下输出:

1.16.1

You can get numpy version using Terminal or a Python code.

In a Terminal (bash) using Ubuntu:

pip list | grep numpy

In python 3.6.7, this code shows the numpy version:

import numpy
print (numpy.version.version)

If you insert this code in the file shownumpy.py, you can compile it:

python shownumpy.py

or

python3 shownumpy.py

I’ve got this output:

1.16.1

回答 9

import numpy
print numpy.__version__
import numpy
print numpy.__version__

回答 10

对于Python 3.X打印语法:

python -c "import numpy; print (numpy.version.version)"

要么

python -c "import numpy; print(numpy.__version__)"

For Python 3.X print syntax:

python -c "import numpy; print (numpy.version.version)"

Or

python -c "import numpy; print(numpy.__version__)"

回答 11

只需对解决方案进行一点更改,即可使用Python检查numpy的版本,

import numpy as np 
print("Numpy Version:",np.__version__)

要么,

import numpy as np
print("Numpy Version:",np.version.version)

我在PyCharm中的项目当前正在运行版本

1.17.4

Just a slight solution change for checking the version of numpy with Python,

import numpy as np 
print("Numpy Version:",np.__version__)

Or,

import numpy as np
print("Numpy Version:",np.version.version)

My projects in PyCharm are currently running version

1.17.4

回答 12

在Python Shell中:

>>> help()
help> numpy

In a Python shell:

>>> help()
help> numpy

回答 13

可以从终端执行的纯Python行(2.X和3.X版本):

python -c "import numpy; print(numpy.version.version)"

如果您已经在Python中,则:

import numpy
print(numpy.version.version)

Pure Python line that can be executed from the terminal (both 2.X and 3.X versions):

python -c "import numpy; print(numpy.version.version)"

If you are already inside Python, then:

import numpy
print(numpy.version.version)

回答 14

很高兴知道numpy您运行的版本,但是严格来说,如果您只需要在系统上具有特定版本,则可以这样编写:

pip install numpy==1.14.3 这将安装您需要的版本,并卸载其他版本的numpy

It is good to know the version of numpy you run, but strictly speaking if you just need to have specific version on your system you can write like this:

pip install numpy==1.14.3 and this will install the version you need and uninstall other versions of numpy.


如何找到我的系统中安装了哪个版本的TensorFlow?

问题:如何找到我的系统中安装了哪个版本的TensorFlow?

我需要找到已安装的TensorFlow版本。我正在使用Ubuntu 16.04长期支持。

I need to find which version of TensorFlow I have installed. I’m using Ubuntu 16.04 Long Term Support.


回答 0

这取决于您安装TensorFlow的方式。我将使用TensorFlow的安装说明所用的相同标题来组织此答案。


点安装

跑:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

请注意,在某些Linux发行版中,它python是符号链接的/usr/bin/python3,因此在这些情况下,请使用python代替python3

pip list | grep tensorflow适用于Python 2或pip3 list | grep tensorflow适用于Python 3的版本还将显示已安装的Tensorflow的版本。


Virtualenv安装

跑:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for both Python 2 and Python 3

pip list | grep tensorflow 还将显示已安装的Tensorflow的版本。

例如,我已经在virtualenvPython 3的a中安装了TensorFlow 0.9.0 。因此,我得到:

$ python -c 'import tensorflow as tf; print(tf.__version__)'
0.9.0

$ pip list | grep tensorflow
tensorflow (0.9.0)

This depends on how you installed TensorFlow. I am going to use the same headings used by TensorFlow’s installation instructions to structure this answer.


Pip installation

Run:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

Note that python is symlinked to /usr/bin/python3 in some Linux distributions, so use python instead of python3 in these cases.

pip list | grep tensorflow for Python 2 or pip3 list | grep tensorflow for Python 3 will also show the version of Tensorflow installed.


Virtualenv installation

Run:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for both Python 2 and Python 3

pip list | grep tensorflow will also show the version of Tensorflow installed.

For example, I have installed TensorFlow 0.9.0 in a virtualenv for Python 3. So, I get:

$ python -c 'import tensorflow as tf; print(tf.__version__)'
0.9.0

$ pip list | grep tensorflow
tensorflow (0.9.0)

回答 1

python中几乎每个普通软件包都将变量.__version__或分配VERSION给当前版本。因此,如果要查找某些软件包的版本,可以执行以下操作

import a
a.__version__ # or a.VERSION

对于张量流它将是

import tensorflow as tf
tf.VERSION

对于旧版本的tensorflow(低于0.10),请使用 tf.__version__

顺便说一句,如果您打算安装TF,请使用conda而不是pip进行安装

Almost every normal package in python assigns the variable .__version__ to the current version. So if you want to find the version of some package you can do the following

import a
a.__version__

For tensorflow it will be

import tensorflow as tf
tf.version.VERSION

For old versions of tensorflow (below 0.10), use tf.__version__


回答 2

如果您是通过pip安装的,则只需运行以下命令

$ pip show tensorflow
Name: tensorflow
Version: 1.5.0
Summary: TensorFlow helps the tensors flow

If you have installed via pip, just run the following

$ pip show tensorflow
Name: tensorflow
Version: 1.5.0
Summary: TensorFlow helps the tensors flow

回答 3

import tensorflow as tf

print(tf.VERSION)
import tensorflow as tf

print(tf.VERSION)

回答 4

如果您使用的是Python的anaconda发行版,

$ conda list | grep tensorflow
tensorflow    1.0.0       py35_0    conda-forge

使用Jupyter Notebook(IPython Notebook)进行检查

In [1]: import tensorflow as tf
In [2]: tf.__version__
Out[2]: '1.0.0'

If you’re using anaconda distribution of Python,

$ conda list | grep tensorflow
tensorflow    1.0.0       py35_0    conda-forge

To check it using Jupyter Notebook (IPython Notebook)

In [1]: import tensorflow as tf
In [2]: tf.__version__
Out[2]: '1.0.0'

回答 5

对于python 3.6.2:

import tensorflow as tf

print(tf.version.VERSION)

For python 3.6.2:

import tensorflow as tf

print(tf.version.VERSION)

回答 6

我从源代码安装了Tensorflow 0.12rc,以下命令为我提供了版本信息:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

下图显示了输出:

在此处输入图片说明

I installed the Tensorflow 0.12rc from source, and the following command gives me the version info:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

The following figure shows the output:

enter image description here


回答 7

在最新的TensorFlow版本1.14.0上

tf.VERSION

已弃用,而不是此用法

tf.version.VERSION

错误:

WARNING: Logging before flag parsing goes to stderr.
The name tf.VERSION is deprecated. Please use tf.version.VERSION instead.

On Latest TensorFlow release 1.14.0

tf.VERSION

is deprecated, instead of this use

tf.version.VERSION

ERROR:

WARNING: Logging before flag parsing goes to stderr.
The name tf.VERSION is deprecated. Please use tf.version.VERSION instead.

回答 8

要获取有关tensorflow及其选项的更多信息,可以使用以下命令:

>> import tensorflow as tf
>> help(tf)

To get more information about tensorflow and its options you can use below command:

>> import tensorflow as tf
>> help(tf)

回答 9

轻松获得KERAS和TENSORFLOW版本号->在终端中运行以下命令:

[用户名@usrnm:〜] python3

>>import keras; print(keras.__version__)

Using TensorFlow backend.

2.2.4

>>import tensorflow as tf; print(tf.__version__)

1.12.0

Easily get KERAS and TENSORFLOW version number –> Run this command in terminal:

[username@usrnm:~] python3

>>import keras; print(keras.__version__)

Using TensorFlow backend.

2.2.4

>>import tensorflow as tf; print(tf.__version__)

1.12.0


回答 10

tensorflow版本可以在终端或控制台上检查,也可以在任何IDE编辑器中检查(例如Spyder或Jupyter笔记本等)

简单命令检查版本:

(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit)

>>> import tensorflow as tf
>>> tf.__version__
'1.13.1'

The tensorflow version can be checked either on terminal or console or in any IDE editer as well (like Spyder or Jupyter notebook, etc)

Simple command to check version:

(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit)

>>> import tensorflow as tf
>>> tf.__version__
'1.13.1'

回答 11

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

-c表示以字符串形式传入的程序(终止选项列表)

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

Here -c represents program passed in as string (terminates option list)


回答 12

Jupyter Notebook中的Tensorflow版本:-

!pip list | grep tensorflow

Tensorflow version in Jupyter Notebook:-

!pip list | grep tensorflow

回答 13

如果您具有TensorFlow 2.x:

sess = tf.compat.v1.Session(config = tf.compat.v1.ConfigProto(log_device_placement = True))

If you have TensorFlow 2.x:

sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))


回答 14

我猜是另一种变化:P

python3 -c 'print(__import__("tensorflow").__version__)'

Another variation, i guess :P

python3 -c 'print(__import__("tensorflow").__version__)'


我已经安装了哪个版本的Python?

问题:我已经安装了哪个版本的Python?

我必须在Windows服务器上运行Python脚本。我怎么知道我拥有哪个版本的Python,它真的很重要吗?

我当时想更新到最新版本的Python。

I have to run a Python script on a Windows server. How can I know which version of Python I have, and does it even really matter?

I was thinking of updating to the latest version of Python.


回答 0

python -V

http://docs.python.org/using/cmdline.html#generic-options

--version 可能也可以使用(在2.5版中引入)

python -V

http://docs.python.org/using/cmdline.html#generic-options

--version may also work (introduced in version 2.5)


回答 1

Python 2.5以上版本:

python --version

Python 2.4-:

python -c 'import sys; print(sys.version)'

Python 2.5+:

python --version

Python 2.4-:

python -c 'import sys; print(sys.version)'

回答 2

在Python IDE中,只需复制并粘贴以下代码并运行它(版本将显示在输出区域中):

import sys
print(sys.version)

In a Python IDE, just copy and paste in the following code and run it (the version will come up in the output area):

import sys
print(sys.version)

回答 3

在命令提示符下键入:

python -V

或者,如果您有pyenv:

pyenv versions

At a command prompt type:

python -V

Or if you have pyenv:

pyenv versions

回答 4

当我打开Python (command line)第一件事时,它会告诉我版本。

When I open Python (command line) the first thing it tells me is the version.


回答 5

尽管问题是“我正在使用哪个版本?”,但这实际上可能并不是您需要知道的所有内容。您可能安装了其他版本,这可能会导致问题,尤其是在安装其他模块时。这是我了解安装了哪些版本的粗略方法:

updatedb                  # Be in root for this
locate site.py            # All installations I've ever seen have this

单个Python安装的输出应如下所示:

/usr/lib64/python2.7/site.py
/usr/lib64/python2.7/site.pyc
/usr/lib64/python2.7/site.pyo

多个安装将输出如下内容:

/root/Python-2.7.6/Lib/site.py
/root/Python-2.7.6/Lib/site.pyc
/root/Python-2.7.6/Lib/site.pyo
/root/Python-2.7.6/Lib/test/test_site.py
/usr/lib/python2.6/site-packages/site.py
/usr/lib/python2.6/site-packages/site.pyc
/usr/lib/python2.6/site-packages/site.pyo
/usr/lib64/python2.6/site.py
/usr/lib64/python2.6/site.pyc
/usr/lib64/python2.6/site.pyo
/usr/local/lib/python2.7/site.py
/usr/local/lib/python2.7/site.pyc
/usr/local/lib/python2.7/site.pyo
/usr/local/lib/python2.7/test/test_site.py
/usr/local/lib/python2.7/test/test_site.pyc
/usr/local/lib/python2.7/test/test_site.pyo

Although the question is “which version am I using?”, this may not actually be everything you need to know. You may have other versions installed and this can cause problems, particularly when installing additional modules. This is my rough-and-ready approach to finding out what versions are installed:

updatedb                  # Be in root for this
locate site.py            # All installations I've ever seen have this

The output for a single Python installation should look something like this:

/usr/lib64/python2.7/site.py
/usr/lib64/python2.7/site.pyc
/usr/lib64/python2.7/site.pyo

Multiple installations will have output something like this:

/root/Python-2.7.6/Lib/site.py
/root/Python-2.7.6/Lib/site.pyc
/root/Python-2.7.6/Lib/site.pyo
/root/Python-2.7.6/Lib/test/test_site.py
/usr/lib/python2.6/site-packages/site.py
/usr/lib/python2.6/site-packages/site.pyc
/usr/lib/python2.6/site-packages/site.pyo
/usr/lib64/python2.6/site.py
/usr/lib64/python2.6/site.pyc
/usr/lib64/python2.6/site.pyo
/usr/local/lib/python2.7/site.py
/usr/local/lib/python2.7/site.pyc
/usr/local/lib/python2.7/site.pyo
/usr/local/lib/python2.7/test/test_site.py
/usr/local/lib/python2.7/test/test_site.pyc
/usr/local/lib/python2.7/test/test_site.pyo

回答 6

In [1]: import sys

In [2]: sys.version
2.7.11 |Anaconda 2.5.0 (64-bit)| (default, Dec  6 2015, 18:08:32) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]

In [3]: sys.version_info
sys.version_info(major=2, minor=7, micro=11, releaselevel='final', serial=0)

In [4]: sys.version_info >= (2,7)
Out[4]: True

In [5]: sys.version_info >= (3,)
Out[5]: False
In [1]: import sys

In [2]: sys.version
2.7.11 |Anaconda 2.5.0 (64-bit)| (default, Dec  6 2015, 18:08:32) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]

In [3]: sys.version_info
sys.version_info(major=2, minor=7, micro=11, releaselevel='final', serial=0)

In [4]: sys.version_info >= (2,7)
Out[4]: True

In [5]: sys.version_info >= (3,)
Out[5]: False

回答 7

简而言之:

键入python在命令提示

只需打开命令提示符(Win+ R)并键入,cmd然后在命令提示符中键入,即可python为您提供有关版本的所有必要信息:

Python版本

In short:

Type python in a command prompt

Simply open the command prompt (Win + R) and type cmd and in the command prompt then typing python will give you all necessary information regarding versions:

Python version


回答 8

>>> import sys; print('{0[0]}.{0[1]}'.format(sys.version_info))
3.5

所以从命令行:

python -c "import sys; print('{0[0]}.{0[1]}'.format(sys.version_info))"
>>> import sys; print('{0[0]}.{0[1]}'.format(sys.version_info))
3.5

so from the command line:

python -c "import sys; print('{0[0]}.{0[1]}'.format(sys.version_info))"

回答 9

采用

python -V

要么

python --version

注意:请注意,python -V命令中的“ V” 为大写V。python -v(小“ v”)将以详细模式启动Python。

Use

python -V

or

python --version

NOTE: Please note that the “V” in the python -V command is capital V. python -v (small “v”) will launch Python in verbose mode.


回答 10

您可以使用以下命令获取Python的版本

python --version

您甚至可以使用以下命令获取venv中安装的任何软件包的版本pip freeze

pip freeze | grep "package name"

或将Python解释器用作:

In [1]: import django
In [2]: django.VERSION
Out[2]: (1, 6, 1, 'final', 0)

You can get the version of Python by using the following command

python --version

You can even get the version of any package installed in venv using pip freeze as:

pip freeze | grep "package name"

Or using the Python interpreter as:

In [1]: import django
In [2]: django.VERSION
Out[2]: (1, 6, 1, 'final', 0)

回答 11

我在Windows 10上使用Python 3.7.0。

这是在命令提示符和Git Bash中对我有用的方法

要运行Python并检查版本:

py

仅检查您拥有的版本:

py --version

要么

py -V    # Make sure it is a capital V

注:pythonpython --versionpython -VPythonPython --versionPython -V并没有为我工作。

I have Python 3.7.0 on Windows 10.

This is what worked for me in the command prompt and Git Bash:

To run Python and check the version:

py

To only check which version you have:

py --version

or

py -V    # Make sure it is a capital V

Note: python, python --version, python -V,Python, Python --version, Python -V did not work for me.


回答 12

如果您已经在REPL窗口中,但没有看到带有版本号的欢迎消息,则可以使用help()查看主要版本和次要版本:

>>>help()
Welcome to Python 3.6's help utility!
...

If you are already in a REPL window and don’t see the welcome message with the version number, you can use help() to see the major and minor version:

>>>help()
Welcome to Python 3.6's help utility!
...

回答 13

要在Jupyter笔记本中检查Python版本,可以使用:

from platform import python_version
print(python_version())

获取版本号,例如:

3.7.3

要么:

import sys
print(sys.version)

以获取更多信息

3.7.3 (default, Apr 24 2019, 13:20:13) [MSC v.1915 32 bit (Intel)]

要么:

sys.version_info

获得主要版本,次要版本和微型版本

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

To check the Python version in a Jupyter notebook, you can use:

from platform import python_version
print(python_version())

to get version number, as:

3.7.3

or:

import sys
print(sys.version)

to get more information, as

3.7.3 (default, Apr 24 2019, 13:20:13) [MSC v.1915 32 bit (Intel)]

or:

sys.version_info

to get major, minor and micro versions, as

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

回答 14

只需创建一个以.py结尾的文件,然后将以下代码粘贴到并运行即可。

#!/usr/bin/python3.6

import platform
import sys

def linux_dist():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"

print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
""" % (
sys.version.split('\n'),
str(platform.dist()),
linux_dist(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
))

如果系统上安装了多个Python解释器版本,请运行以下命令。

在Linux上,在终端上运行:

ll /usr/bin/python*

在Windows上,在命令提示符下运行:

dir %LOCALAPPDATA%\Programs\Python

Just create a file ending with .py and paste the code below into and run it.

#!/usr/bin/python3.6

import platform
import sys

def linux_dist():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"

print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
""" % (
sys.version.split('\n'),
str(platform.dist()),
linux_dist(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
))

If several Python interpreter versions are installed on a system, run the following commands.

On Linux, run in a terminal:

ll /usr/bin/python*

On Windows, run in a command prompt:

dir %LOCALAPPDATA%\Programs\Python

回答 15

要在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'

To verify the Python version for commands on Windows, run the following commands in a command prompt and verify the output:

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:

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

回答 16

在具有Python 3.6的Windows 10上

    python

Python 3.6.0a4 (v3.6.0a4:017cf260936b, Aug 16 2016, 00:59:16) [MSC v.1900 64 bit (AMD64)] on win32


    python -V

Python 3.6.0a4


    python --version

Python 3.6.0a4

On Windows 10 with Python 3.6

    python

Python 3.6.0a4 (v3.6.0a4:017cf260936b, Aug 16 2016, 00:59:16) [MSC v.1900 64 bit (AMD64)] on win32


    python -V

Python 3.6.0a4


    python --version

Python 3.6.0a4

回答 17

如果已安装Python,则检查版本号的最简单方法是在命令提示符下键入“ python”。它会显示版本号,以及它是在32位还是64位上运行以及其他信息。对于某些应用程序,您可能需要具有最新版本,而有时却没有。这取决于您要安装或使用的软件包。

If you have Python installed then the easiest way you can check the version number is by typing “python” in your command prompt. It will show you the version number and if it is running on 32 bit or 64 bit and some other information. For some applications you would want to have a latest version and sometimes not. It depends on what packages you want to install or use.


回答 18

对我来说,打开CMD并运行

py

将显示类似

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

For me, opening CMD and running

py

will show something like

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

回答 19

打开命令提示符窗口(按Windows+ R,输入cmd,然后单击Enter)。

类型 python.exe

Open a command prompt window (press Windows + R, type in cmd, and hit Enter).

Type python.exe


回答 20

打字 where python在Windows上命令提示符可能会告诉您在哪里安装了多个不同版本的python,前提是它们已添加到您的路径中。

键入python -V命令提示符将显示版本。

Typing where python on Windows into a Command Prompt may tell you where multiple different versions of python are installed, assuming they have been added to your path.

Typing python -V into the Command Prompt should display the version.


回答 21

主要是用法命令:

python -version

要么

python -V

Mostly usage commands:

python -version

Or

python -V

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

问题:如何检查正在运行脚本的Python版本?

如何检查正在解释脚本的版本的Python Interpreter?

How can I check what version of the Python Interpreter is interpreting my script?


回答 0

sys模块的sys.version字符串中提供了此信息:

>>> import sys

可读性:

>>> 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)]

进行进一步处理:

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

为确保脚本以Python解释器的最低版本要求运行,请将其添加到您的代码中:

assert sys.version_info >= (2, 5)

这将比较主要版本和次要版本信息。微(=添加01等等),甚至releaselevel(= 'alpha''final'等)的元组只要你喜欢。但是请注意,最好总是“躲开”检查是否存在某个功能,如果不存在,则要变通(或纾困)。有时,某些功能在较新的版本中会消失,而被其他功能取代。

This information is available in the sys.version string in the sys module:

>>> 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:

>>> 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:

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. 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.


回答 1

在命令行中(注意大写的“ V”):

python -V

在’man python’中有记录。

From the command line (note the capital ‘V’):

python -V

This is documented in ‘man python’.


回答 2

我喜欢这样sys.hexversion的东西。

http://docs.python.org/library/sys.html#sys.hexversion

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

I like sys.hexversion for stuff like this.

http://docs.python.org/library/sys.html#sys.hexversion

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

回答 3

您最好的选择可能是这样的:

>>> 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
>>> 

此外,您始终可以通过简单的尝试将导入文件包装起来,这样可以捕获语法错误。而且,就@Heikki而言,此代码将与许多旧版本的python兼容:

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

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:

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

回答 4

使用platformpython_version从STDLIB:

>>> from platform import python_version
>>> print(python_version())
2.7.8

Use platform‘s python_version from the stdlib:

>>> from platform import python_version
>>> print(python_version())
2.7.8

回答 5

放入类似:

#!/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甚至可能无法加载脚本,因此无法报告该错误。解决方法是,您可以在脚本中运行以上命令,该脚本将使用更现代的代码导入该脚本。

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. As a workaround, you can run the above in a script that imports the script with the more modern code.


回答 6

这是一个简短的命令行版本,可以立即退出(对于脚本和自动执行非常方便):

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

或者只是主要,次要和微观:

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)

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)

回答 7

使用six模块,您可以通过以下方法实现:

import six

if six.PY2:
  # this is python2.x
else:
  # six.PY3
  # this is python3.x

With six module, you can do it by:

import six

if six.PY2:
  # this is python2.x
else:
  # six.PY3
  # this is python3.x

回答 8

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

sys.version提供您想要的,只需选择第一个数字即可:)

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

sys.version gives you what you want, just pick the first number :)


回答 9

最简单的方法

只需在终端中键入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.
>>> 

The simplest way

Just type python in your terminal and you can see the version as like following

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.
>>> 

回答 10

就像Seth所说的那样,主脚本可以检查sys.version_info(但是请注意,直到2.0才出现),因此,如果要支持旧版本,则需要检查sys模块的另一个版本属性。

但是,您仍然需要注意不要使用该文件中的任何Python语言功能,这些功能在较早的Python版本中不可用。例如,在Python 2.5和更高版本中允许这样做:

try:
    pass
except:
    pass
finally:
    pass

但在较旧的Python版本中将无法使用,因为您只能使用OR或最终与try匹配。因此,为了与旧版本的Python兼容,您需要编写:

try:
    try:
        pass
    except:
        pass
finally:
    pass

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).

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. For example, this is allowed in Python 2.5 and later:

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. So for compatibility with older Python versions you need to write:

try:
    try:
        pass
    except:
        pass
finally:
    pass

回答 11

一些答案已经建议如何查询当前的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")

Several answers already suggest how to query the current python version. 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")

回答 12

只是为了好玩,下面是在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")

Just for fun, the following is a way of doing it on CPython 1.0-3.7b2, Pypy, Jython and 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:

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

回答 13

检查Python版本:python -Vpython --versionapt-cache policy python

您还可以运行whereis python以查看安装了多少个版本。

Check Python version: python -V or python --version or apt-cache policy python

you can also run whereis python to see how many versions are installed.


回答 14

如果您想检测Python 3之前的版本并且不想导入任何东西…

…您可以(ab)使用列表理解范围的更改,并在单个表达式中完成

is_python_3_or_above = (lambda x: [x for x in [False]] and None or x)(True)

If you want to detect pre-Python 3 and don’t want to import anything…

…you can (ab)use list comprehension scoping changes and do it in a single expression:

is_python_3_or_above = (lambda x: [x for x in [False]] and None or x)(True)

回答 15

要在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'

To verify the Python version for commands on Windows, run the following commands in a command prompt and verify the output

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:

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

回答 16

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

输出

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
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

回答 17

sys.version_infotuple从3.7开始似乎没有返回a 。相反,它返回一个特殊的类,因此至少对于我来说,所有使用元组的示例都不起作用。这是python控制台的输出:

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

我发现结合使用sys.version_info.majorsys.version_info.minor似乎足够了。例如,…

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

检查您是否正在运行Python3。您甚至可以使用…检查更特定的版本。

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)

可以检查您是否至少运行Python 3.5。

sys.version_info doesn’t seem to return a tuple as of 3.7. 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:

>>> 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. 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…

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.


回答 18

最简单的方法:

在Spyder中,启动新的“ IPython Console”,然后运行任何现有脚本。

现在,可以在控制台窗口中打印的第一个输出中看到版本:

“ Python 3.7.3(默认值,2019年4月24日,15:29:51)…”

在此处输入图片说明

The even simpler simplest way:

In Spyder, start a new “IPython Console”, then run any of your existing scripts.

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)…”

enter image description here


回答 19

要从命令行检查,只需一个命令,但要包含主要,次要,微型版本,发行版和序列号

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

3.7.6-final-0

注意:.format()代替f字符串,或者'.'.join()允许您使用任意格式和分隔符char,例如,使其成为可抓握的单字字符串。我将其放在报告所有重要版本的bash实用程序脚本中:python,numpy,pandas,sklearn,MacOS,xcode,clang,brew,conda,anaconda,gcc / g ++等。对于日志记录,可复制性,故障排除报告等很有用。

To check from the command-line, in one single command, but include major, minor, micro version, releaselevel and serial:

> 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, e.g. to make this a greppable one-word string. 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.


回答 20

如果您在linux上工作,请给出命令python 输出将如下所示

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

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

键入“帮助”,“版权”,“信用”或“许可证”以获取更多信息。

If you are working on linux just give command python output will be like this

Python 2.4.3 (#1, Jun 11 2009, 14:09:37)

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

Type “help”, “copyright”, “credits” or “license” for more information.