问题:如何检查python模块的版本?

我刚安装的Python模块:constructstatlibsetuptools这样的:

# Install setuptools to be able to download the following
sudo apt-get install python-setuptools

# Install statlib for lightweight statistical tools
sudo easy_install statlib

# Install construct for packing/unpacking binary data
sudo easy_install construct

我希望能够(以编程方式)检查其版本。是否有一个相当于python --version我可以在命令行中运行?

我的python版本是2.7.3

I just installed the python modules: construct and statlib with setuptools like this:

# Install setuptools to be able to download the following
sudo apt-get install python-setuptools

# Install statlib for lightweight statistical tools
sudo easy_install statlib

# Install construct for packing/unpacking binary data
sudo easy_install construct

I want to be able to (programmatically) check their versions. Is there an equivalent to python --version I can run from the command line?

My python version is 2.7.3.


回答 0

我建议使用pip代替easy_install。使用pip,您可以列出所有已安装的软件包及其版本

pip freeze

在大多数linux系统中,您可以将此管道传送到grep(或findstr在Windows上)以找到您感兴趣的特定软件包的行:

Linux:
$ pip freeze | grep lxml
lxml==2.3

Windows:
c:\> pip freeze | findstr lxml
lxml==2.3

对于单个模块,可以尝试使用__version__属性,但是有些模块没有该属性

$ python -c "import requests; print(requests.__version__)"
2.14.2
$ python -c "import lxml; print(lxml.__version__)"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: 'module' object has no attribute '__version__'

最后,由于问题中的命令带有前缀sudo,因此您似乎正在安装到全局python环境。强烈建议研究python 虚拟环境管理器,例如virtualenvwrapper

I suggest using pip in place of easy_install. With pip, you can list all installed packages and their versions with

pip freeze

In most linux systems, you can pipe this to grep(or findstr on Windows) to find the row for the particular package you’re interested in:

Linux:
$ pip freeze | grep lxml
lxml==2.3

Windows:
c:\> pip freeze | findstr lxml
lxml==2.3

For an individual module, you can try the __version__ attribute, however there are modules without it:

$ python -c "import requests; print(requests.__version__)"
2.14.2
$ python -c "import lxml; print(lxml.__version__)"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: 'module' object has no attribute '__version__'

Lastly, as the commands in your question are prefixed with sudo, it appears you’re installing to the global python environment. Strongly advise to take look into python virtual environment managers, for example virtualenvwrapper


回答 1

你可以试试

>>> import statlib
>>> print statlib.__version__

>>> import construct
>>> print contruct.__version__

You can try

>>> import statlib
>>> print statlib.__version__

>>> import construct
>>> print contruct.__version__

回答 2

使用库一起分发的模块。请注意,传递给get_distribution方法的字符串应对应于PyPI条目。

>>> import pkg_resources
>>> pkg_resources.get_distribution("construct").version
'2.5.2'

如果要从命令行运行它,可以执行以下操作:

python -c "import pkg_resources; print(pkg_resources.get_distribution('construct').version)"

请注意,传递给该get_distribution方法的字符串应该是在PyPI中注册的包名称,而不是您要导入的模块名称。

不幸的是,这些并不总是相同的(例如,您可以pip install memcached,但是import memcache)。

Use module distributed with library. Note that the string that you pass to get_distribution method should correspond to the PyPI entry.

>>> import pkg_resources
>>> pkg_resources.get_distribution("construct").version
'2.5.2'

and if you want to run it from the command line you can do:

python -c "import pkg_resources; print(pkg_resources.get_distribution('construct').version)"

Note that the string that you pass to the get_distribution method should be the package name as registered in PyPI, not the module name that you are trying to import.

Unfortunately these aren’t always the same (e.g. you do pip install memcached, but import memcache).


回答 3

我认为这可以帮助您,但请先安装show软件包才能运行,pip show然后使用show查找版本!

sudo pip install show
# in order to get package version execute the below command
sudo pip show YOUR_PACKAGE_NAME | grep Version

I think this can help but first install show package in order to run pip show then use show to find the version!

sudo pip install show
# in order to get package version execute the below command
sudo pip show YOUR_PACKAGE_NAME | grep Version

回答 4

更好的方法是:


有关特定包装的详细信息

它详细列出了Package_name,版本,作者,位置等。




pip 应该对此进行更新。

pip install --upgrade pip

在Windows上,推荐的命令是:

python -m pip install --upgrade pip

The Better way to do that is:


For the details of specific Package

It details out the Package_name, Version, Author, Location etc.




pip should be updated to do this.
pip install --upgrade pip

On Windows recommend command is:

python -m pip install --upgrade pip


回答 5

在python3中带有括号的打印

>>> import celery
>>> print(celery.__version__)
3.1.14

In python3 with brackets around print

>>> import celery
>>> print(celery.__version__)
3.1.14

回答 6

module.__version__ 首先尝试尝试是一件好事,但它并不总是有效。

如果您不希望掏空,并且使用的是pip 8或9,则仍然可以使用pip.get_installed_distributions()Python中的版本来获取版本:

更新: 此处的解决方案适用于第8点和第9点,但在第10点中,该功能已从移至pip.get_installed_distributionspip._internal.utils.misc.get_installed_distributions以明确指示该功能不供外部使用。如果您使用的是pip 10+,则不是一个好主意。

import pip

pip.get_installed_distributions()  # -> [distribute 0.6.16 (...), ...]

[
    pkg.key + ': ' + pkg.version
    for pkg in pip.get_installed_distributions()
    if pkg.key in ['setuptools', 'statlib', 'construct']
] # -> nicely filtered list of ['setuptools: 3.3', ...]

module.__version__ is a good first thing to try, but it doesn’t always work.

If you don’t want to shell out, and you’re using pip 8 or 9, you can still use pip.get_installed_distributions() to get versions from within Python:

update: the solution here works in pip 8 and 9, but in pip 10 the function has been moved from pip.get_installed_distributions to pip._internal.utils.misc.get_installed_distributions to explicitly indicate that it’s not for external use. It’s not a good idea to rely on it if you’re using pip 10+.

import pip

pip.get_installed_distributions()  # -> [distribute 0.6.16 (...), ...]

[
    pkg.key + ': ' + pkg.version
    for pkg in pip.get_installed_distributions()
    if pkg.key in ['setuptools', 'statlib', 'construct']
] # -> nicely filtered list of ['setuptools: 3.3', ...]

回答 7

先前的答案不能解决我的问题,但是这段代码可以解决:

import sys 
for name, module in sorted(sys.modules.items()): 
  if hasattr(module, '__version__'): 
    print name, module.__version__ 

The previous answers did not solve my problem, but this code did:

import sys 
for name, module in sorted(sys.modules.items()): 
  if hasattr(module, '__version__'): 
    print name, module.__version__ 

回答 8

您可以importlib_metadata为此使用库。

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

pip install importlib_metadata

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

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

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

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

You can use importlib_metadata library for this.

If you’re on python <3.8, first install it with:

pip install importlib_metadata

Since python 3.8 it’s included in the standard library.

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


回答 9

使用dir()以找出是否该模块具有__version__的所有属性。

>>> import selenium
>>> dir(selenium)
['__builtins__', '__doc__', '__file__', '__name__',
 '__package__', '__path__', '__version__']
>>> selenium.__version__
'3.141.0'
>>> selenium.__path__
['/venv/local/lib/python2.7/site-packages/selenium']

Use dir() to find out if the module has a __version__ attribute at all.

>>> import selenium
>>> dir(selenium)
['__builtins__', '__doc__', '__file__', '__name__',
 '__package__', '__path__', '__version__']
>>> selenium.__version__
'3.141.0'
>>> selenium.__path__
['/venv/local/lib/python2.7/site-packages/selenium']

回答 10

如果上述方法不起作用,则值得在python中尝试以下方法:

import modulename

modulename.version
modulename.version_info

请参阅获取Python Tornado版本?

请注意,.version除了龙卷风以外,它还为我在其他几个项目上起作用。

If the above methods do not work, it is worth trying the following in python:

import modulename

modulename.version
modulename.version_info

See Get Python Tornado Version?

Note, the .version worked for me on a few others besides tornado as well.


回答 11

首先添加python,将pip添加到您的环境变量中。这样您就可以从命令提示符下执行命令。然后只需给出python命令。然后导入包

->import scrapy

然后打印版本名称

->print(scrapy.__version__)

这肯定会工作

first add python, pip to your environment variables. so that you can execute your commands from command prompt. then simply give python command. then import the package

–>import scrapy

then print the version name

–>print(scrapy.__version__)

This will definitely work


回答 12

假设我们正在使用Jupyter Notebook(如果使用Terminal,请删除感叹号):

1)如果软件包(例如xgboost)是通过pip安装的:

!pip show xgboost
!pip freeze | grep xgboost
!pip list | grep xgboost

2)如果软件包(例如caffe)与conda一起安装:

!conda list caffe

Assuming we are using Jupyter Notebook (if using Terminal, drop the exclamation marks):

1) if the package (e.g. xgboost) was installed with pip:

!pip show xgboost
!pip freeze | grep xgboost
!pip list | grep xgboost

2) if the package (e.g. caffe) was installed with conda:

!conda list caffe

回答 13

有些模块没有__version__属性,所以最简单的方法是在终端中检查:pip list

Some modules don’t have __version__ attribute, so the easiest way is check in the terminal: pip list


回答 14

在Python 3.8版本中,importlib软件包中有一个新模块,它也可以做到这一点。

这是docs中的示例:

>>> from importlib.metadata import version
>>> version('requests')
'2.22.0'

In Python 3.8 version there is a new module in importlib package, which can do that as well.

Here is an example from docs:

>>> from importlib.metadata import version
>>> version('requests')
'2.22.0'

回答 15

我建议python在终端(您感兴趣的python版本)中打开一个shell,导入该库并获取其__version__属性。

>>> import statlib
>>> statlib.__version__

>>> import construct
>>> contruct.__version__

注意1:我们必须考虑python版本。如果安装了不同版本的python,则必须使用感兴趣的python版本打开终端。例如,使用python3.8can(肯定会)打开终端会提供与使用python3.5or 相比不同的库版本python2.7

注意2:我们避免使用print函数,因为它的行为取决于python2或python3。我们不需要它,终端将显示表达式的值。

I suggest opening a python shell in terminal (in the python version you are interested), importing the library, and getting its __version__ attribute.

>>> import statlib
>>> statlib.__version__

>>> import construct
>>> contruct.__version__

Note 1: We must regard the python version. If we have installed different versions of python, we have to open the terminal in the python version we are interested in. For example, opening the terminal with python3.8 can (surely will) give a different version of a library than opening with python3.5 or python2.7.

Note 2: We avoid using the print function, because its behavior depends on python2 or python3. We do not need it, the terminal will show the value of the expression.


回答 16

这也适用于Windows上的Jupyter Notebook!只要从兼容bash的命令行(如Git Bash(MingW64))启动Jupyter,就可以通过一些细微调整在Windows系统上的Jupyter Notebook中使用许多答案中给出的解决方案。

我正在运行Windows 10 Pro,并且通过Anaconda安装了Python,并且当我通过Git Bash启动Jupyter时,以下代码有效(但是从Anaconda提示符启动时不起作用)。

调整:!在其前面添加一个感叹号()pip以使其成为!pip

>>>!pip show lxml | grep Version
Version: 4.1.0

>>>!pip freeze | grep lxml
lxml==4.1.0

>>>!pip list | grep lxml
lxml                               4.1.0                  

>>>!pip show lxml
Name: lxml
Version: 4.1.0
Summary: Powerful and Pythonic XML processing library combining libxml2/libxslt with the ElementTree API.
Home-page: http://lxml.de/
Author: lxml dev team
Author-email: lxml-dev@lxml.de
License: BSD
Location: c:\users\karls\anaconda2\lib\site-packages
Requires: 
Required-by: jupyter-contrib-nbextensions

This works in Jupyter Notebook on Windows, too! As long as Jupyter is launched from a bash-compliant command line such as Git Bash (MingW64), the solutions given in many of the answers can be used in Jupyter Notebook on Windows systems with one tiny tweak.

I’m running windows 10 Pro with Python installed via Anaconda, and the following code works when I launch Jupyter via Git Bash (but does not when I launch from the Anaconda prompt).

The tweak: Add an exclamation mark (!) in front of pip to make it !pip.

>>>!pip show lxml | grep Version
Version: 4.1.0

>>>!pip freeze | grep lxml
lxml==4.1.0

>>>!pip list | grep lxml
lxml                               4.1.0                  

>>>!pip show lxml
Name: lxml
Version: 4.1.0
Summary: Powerful and Pythonic XML processing library combining libxml2/libxslt with the ElementTree API.
Home-page: http://lxml.de/
Author: lxml dev team
Author-email: lxml-dev@lxml.de
License: BSD
Location: c:\users\karls\anaconda2\lib\site-packages
Requires: 
Required-by: jupyter-contrib-nbextensions

回答 17

快速的python程序列出所有包装(您可以将其复制到requirements.txt

from pip._internal.utils.misc import get_installed_distributions
print_log = ''
for module in sorted(get_installed_distributions(), key=lambda x: x.key): 
    print_log +=  module.key + '~=' + module.version  + '\n'
print(print_log)

输出如下:

asn1crypto~=0.24.0
attrs~=18.2.0
automat~=0.7.0
beautifulsoup4~=4.7.1
botocore~=1.12.98

Quick python program to list all packges (you can copy it to requirements.txt)

from pip._internal.utils.misc import get_installed_distributions
print_log = ''
for module in sorted(get_installed_distributions(), key=lambda x: x.key): 
    print_log +=  module.key + '~=' + module.version  + '\n'
print(print_log)

The output would look like:

asn1crypto~=0.24.0
attrs~=18.2.0
automat~=0.7.0
beautifulsoup4~=4.7.1
botocore~=1.12.98

回答 18

(另请参阅https://stackoverflow.com/a/56912280/7262247

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

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

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

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

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

(see also https://stackoverflow.com/a/56912280/7262247)

I found it quite unreliable to use the various tools available (including the best one pkg_resources mentioned by Jakub Kukul’ 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.


回答 19

要获取当前模块中导入的非标准(点子)模块的列表:

[{pkg.key : pkg.version} for pkg in pip.get_installed_distributions() 
   if pkg.key in set(sys.modules) & set(globals())]

结果:

>>> import sys, pip, nltk, bs4
>>> [{pkg.key : pkg.version} for pkg in pip.get_installed_distributions() if pkg.key in set(sys.modules) & set(globals())]
[{'pip': '9.0.1'}, {'nltk': '3.2.1'}, {'bs4': '0.0.1'}]

注意:

此代码是从此页面上的解决方案以及如何列出导入的模块?

To get a list of non-standard (pip) modules imported in the current module:

[{pkg.key : pkg.version} for pkg in pip.get_installed_distributions() 
   if pkg.key in set(sys.modules) & set(globals())]

Result:

>>> import sys, pip, nltk, bs4
>>> [{pkg.key : pkg.version} for pkg in pip.get_installed_distributions() if pkg.key in set(sys.modules) & set(globals())]
[{'pip': '9.0.1'}, {'nltk': '3.2.1'}, {'bs4': '0.0.1'}]

Note:

This code was put together from solutions both on this page and from How to list imported modules?


回答 20

基于Jakub Kukul的回答,我找到了解决此问题的更可靠方法。

这种方法的主要问题是需要“常规”安装软件包(并且不包括using pip install --user),或者在Python初始化时将其置于系统PATH中。

要绕开它,您可以使用pkg_resources.find_distributions(path_to_search)。这基本上path_to_search是在系统PATH中搜索可导入的发行版。

我们可以像这样遍历这个生成器:

avail_modules = {}
distros = pkg_resources.find_distributions(path_to_search)
for d in distros:
    avail_modules[d.key] = d.version

这将返回一个以模块为键,其版本为值的字典。这种方法可以扩展到版本号之外。

感谢Jakub Kukul指出正确的方向

Building on Jakub Kukul’s answer I found a more reliable way to solve this problem.

The main problem of that approach is that requires the packages to be installed “conventionally” (and that does not include using pip install --user), or be in the system PATH at Python initialisation.

To get around that you can use pkg_resources.find_distributions(path_to_search). This basically searches for distributions that would be importable if path_to_search was in the system PATH.

We can iterate through this generator like this:

avail_modules = {}
distros = pkg_resources.find_distributions(path_to_search)
for d in distros:
    avail_modules[d.key] = d.version

This will return a dictionary having modules as keys and their version as value. This approach can be extended to a lot more than version number.

Thanks to Jakub Kukul for pointing to the right direction


回答 21

综上所述:

conda list   

(它将提供所有库以及版本详细信息)。

和:

pip show tensorflow

(它提供了完整的库详细信息)。

In Summary:

conda list   

(It will provide all the libraries along with version details).

And:

pip show tensorflow

(It gives complete library details).


回答 22

为Windows用户编写此答案。正如所有其他答案中所建议的那样,您可以使用以下语句:

import [type the module name]
print(module.__version__)      # module + '.' + double underscore + version + double underscore

但是,有些模块即使使用上述方法后也不会打印其版本。因此,您可以简单地执行以下操作:

  1. 打开命令提示符。
  2. 使用cd [ 文件地址 ] 导航到文件地址/目录,在该文件中,您已安装了python和所有支持的模块。
  3. 使用命令“ pip install [模块名称] ”,然后按Enter。
  4. 这将向您显示一条消息:“ 已满足要求:文件地址\文件夹名称(带有版本) ”。
  5. 例如,请参见下面的屏幕截图:我必须知道预安装模块的版本,名称为“ Selenium-Screenshot”。它正确显示为1.5.0:

命令提示符屏幕截图

Writing this answer for windows users. As suggested in all other answers, you can use the statements as:

import [type the module name]
print(module.__version__)      # module + '.' + double underscore + version + double underscore

But, there are some modules which don’t print their version even after using the method above. So, what you can simply do is:

  1. Open the command prompt.
  2. Navigate to the file address/directory by using cd [file address] where you’ve kept your python and all supporting modules installed.
  3. use the command “pip install [module name]” and hit enter.
  4. This will show you a message as “Requirement already satisfied: file address\folder name (with version)“.
  5. See the screenshot below for ex: I had to know the version of a pre-installed module named as “Selenium-Screenshot”. It showed me correctly as 1.5.0:

command prompt screenshot


回答 23

您可以尝试以下方法:

pip list

这将输出所有软件包及其版本。 输出量

You can try this:

pip list

This will output all the packages with their versions. Output


回答 24

您可以先安装类似这样的软件包,然后检查其版本

pip install package
import package
print(package.__version__)

它应该给你包的版本

you can first install some package like this and then check its version

pip install package
import package
print(package.__version__)

it should give you package version


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。