[英]How do I check the versions of Python modules?
I installed the Python modules construct
and statlib
using setuptools
:我使用
setuptools
安装了 Python 模块construct
和statlib
:
sudo apt-get install python-setuptools
sudo easy_install statlib
sudo easy_install construct
How do I check their versions from the command line?如何从命令行检查它们的版本?
Use pip
instead of easy_install
.使用
pip
而不是easy_install
。
With pip, list all installed packages and their versions via:使用 pip,通过以下方式列出所有已安装的软件包及其版本:
pip freeze
On 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 系统上,您可以将其通过管道传递给
grep
(或 Windows 上的findstr
)以查找您感兴趣的特定包的行。
pip freeze | grep lxml
lxml==2.3
lxml==2.3
pip freeze | findstr lxml
lxml==2.3
lxml==2.3
For an individual module, you can try the __version__
attribute .对于单个模块,您可以尝试
__version__
属性。 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><module> 中的文件“<string>”,第 1 行
AttributeError: 'module' object has no attribute ' version 'AttributeError:“模块”对象没有属性“版本”
Lastly, as the commands in your question are prefixed with sudo
, it appears you're installing to the global python environment.最后,由于您问题中的命令以
sudo
为前缀,因此您似乎正在安装到全局 python 环境。 I strongly advise to take look into Python virtual environment managers, for example virtualenvwrapper .我强烈建议研究 Python虚拟环境管理器,例如virtualenvwrapper 。
You can try你可以试试
>>> import statlib
>>> print statlib.__version__
>>> import construct
>>> print contruct.__version__
This is the approach recommended by PEP 396 .这是PEP 396推荐的方法。 But that PEP was never accepted and has been deferred.
但该 PEP 从未被接受并被推迟。 In fact, there appears to be increasing support amongst Python core developers to recommend not including a
__version__
attribute, eg in Remove importlib_metadata.事实上,似乎越来越多的 Python 核心开发人员支持建议不要包含
__version__
属性,例如在Remove importlib_metadata 中。 version . 版本。 .
.
Python >= 3.8:蟒蛇> = 3.8:
If you're on Python >= 3.8, you can use a module from the built-in library for that.如果您使用的是 Python >= 3.8,则可以为此使用内置库中的模块。 To check a package's version (in this example
construct
) run:要检查包的版本(在此示例中为
construct
),请运行:
>>> from importlib.metadata import version
>>> version('construct')
'4.3.1'
Python < 3.8: Python < 3.8:
Use pkg_resources
module distributed with setuptools
library.使用与
setuptools
库一起分发的pkg_resources
模块。 Note that the string that you pass to get_distribution
method should correspond to the PyPI entry.请注意,您传递给
get_distribution
方法的字符串应该对应于 PyPI 条目。
>>> import pkg_resources
>>> pkg_resources.get_distribution('construct').version
'2.5.2'
Side notes:旁注:
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.请注意,您传递给
get_distribution
方法的字符串应该是在 PyPI 中注册的包名称,而不是您尝试导入的模块名称。 Unfortunately, these aren't always the same (eg you do pip install memcached
, but import memcache
).不幸的是,这些并不总是相同的(例如,您执行
pip install memcached
,但import memcache
)。
If you want to apply this solution from the command line you can do something like:如果您想从命令行应用此解决方案,您可以执行以下操作:
python -c \
"import pkg_resources; print(pkg_resources.get_distribution('construct').version)"
Use pip show
to find the version!使用
pip show
查找版本!
# In order to get the package version, execute the below command
pip show YOUR_PACKAGE_NAME | grep Version
You can use pip show YOUR_PACKAGE_NAME
- which gives you all details of package.您可以使用
pip show YOUR_PACKAGE_NAME
- 它为您提供包的所有详细信息。 This also works in Windows.这也适用于 Windows。
grep Version
is used in Linux to filter out the version and show it. grep Version
在 Linux 中用于过滤掉版本并显示出来。
The better way to do that is:更好的方法是:
For the details of a specific package有关特定套餐的详细信息
pip show <package_name>
It details out the package_name, version, author, location, etc.它详细说明了 package_name、版本、作者、位置等。
$ pip show numpy
Name: numpy
Version: 1.13.3
Summary: NumPy: array processing for numbers, strings, records, and objects.
Home-page: http://www.numpy.org
Author: NumPy Developers
Author-email: numpy-discussion@python.org
License: BSD
Location: c:\users\prowinjvm\appdata\local\programs\python\python36\lib\site-packages
Requires:
For more details:
>>> pip help
更多详情:
>>> pip help
pip
should be updated to do this.应更新
pip
以执行此操作。
pip install --upgrade pip
On Windows the recommended command is:在 Windows 上,推荐的命令是:
python -m pip install --upgrade pip
In Python 3 with brackets around print:在 Python 3 中,print 周围有括号:
>>> import celery
>>> print(celery.__version__)
3.1.14
module.__version__
is a good first thing to try, but it doesn't always work. module.__version__
是一个很好的尝试,但它并不总是有效。
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:如果您不想掏空,并且您正在使用 pip 8 或 9,您仍然可以使用
pip.get_installed_distributions()
从 Python 中获取版本:
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.此处的解决方案适用于 pip 8 和 9,但在 pip 10 中,该功能已从
pip.get_installed_distributions
移至pip._internal.utils.misc.get_installed_distributions
以明确表明它不是供外部使用的。 It's not a good idea to rely on it if you're using pip 10+.如果您使用的是 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', ...]
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__
Use dir()
to find out if the module has a __version__
attribute at all.使用
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']
You can use this command in Command prompt 您可以在命令提示符中使用此命令
pip show Modulename
ex : pip show xlrd
例如:
pip show xlrd
you will get output like this with all details. 你会得到这样的输出所有细节。
Name: xlrd
Version: 1.2.0
Summary: Library for developers to extract data from Microsoft Excel (tm) spreadsheet files
Home-page: http://www.python-excel.org/
Author: John Machin
Author-email: sjmachin@lexicon.net
License: BSD
Location: c:\users\rohit.chaurasiya\appdata\local\programs\python\python37\lib\site-packages
Requires:
Required-by:
If the methods in previous answers do not work, it is worth trying the following in Python:如果先前答案中的方法不起作用,则值得在 Python 中尝试以下方法:
import modulename
modulename.version
modulename.version_info
See Get the Python Tornado version请参阅获取 Python Tornado 版本
Note, the .version
worked for me on a few others, besides Tornado as well.请注意,除了Tornado之外,
.version
也适用于我的其他一些。
有些模块没有__version__
属性,所以最简单的方法是在终端中检查: pip list
First add executables python
and pip
to your environment variables.首先将可执行文件
python
和pip
添加到您的环境变量中。 So that you can execute your commands from command prompt.这样您就可以从命令提示符执行命令。 Then simply give Python command.
然后简单地给出 Python 命令。
Then import the package:然后导入包:
import scrapy
Then print the version name然后打印版本名称
print(scrapy.__version__)
This will definitely work.这肯定会奏效。
Assuming we are using Jupyter Notebook (if using Terminal, drop the exclamation marks):假设我们使用的是Jupyter Notebook (如果使用终端,请删除感叹号):
You can use importlib_metadata
library for this. 您可以使用
importlib_metadata
库。
If you're on python <3.8
, first install it with: 如果您使用的是python
<3.8
,请首先安装:
pip install importlib_metadata
Since python 3.8
it's included in the standard library. 从python
3.8
它包含在标准库中。
Then, to check a package's version (in this example lxml
) run: 然后,检查包的版本(在本例中为
lxml
)运行:
>>> from importlib_metadata import version
>>> version('lxml')
'4.3.1'
Keep in mind that this works only for packages installed from PyPI. 请记住,这仅适用于从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). 此外,您必须将包名称作为参数传递给
version
方法,而不是此包提供的模块名称(尽管它们通常是相同的)。
I suggest opening a Python shell in the terminal (in the Python version you are interested), importing the library, and getting its __version__
attribute.我建议在终端中打开一个 Python shell(在您感兴趣的 Python 版本中),导入库并获取其
__version__
属性。
>>> import statlib
>>> statlib.__version__
>>> import construct
>>> contruct.__version__
Note 1: We must regard the Python version .注意 1:我们必须考虑Python 版本。 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 Python 3.8 can (surely will) give a different version of a library than opening with Python 3.5 or Python 2.7.
如果我们安装了不同版本的 Python,我们必须在我们感兴趣的 Python 版本中打开终端。例如,用 Python 3.8 打开终端可以(肯定会)提供与用 Python 3.5 打开不同版本的库或 Python 2.7。
Note 2: We avoid using the print
function , because its behavior depends on Python 2 or Python 3. We do not need it, and the terminal will show the value of the expression.注意 2:我们避免使用
print
函数,因为它的行为取决于 Python 2 或 Python 3。我们不需要它,终端会显示表达式的值。
When you install Python, you also get the Python package manager, pip. 当您安装Python时,您还可以获得Python包管理器pip。 You can use pip to get the versions of python modules.
您可以使用pip来获取python模块的版本。 If you want to list all installed Python modules with their version numbers, use the following command:
如果要列出所有已安装的Python模块及其版本号,请使用以下命令:
$ pip freeze
You will get the output: 你会得到输出:
asn1crypto==0.22.0
astroid==1.5.2
attrs==16.3.0
Automat==0.5.0
backports.functools-lru-cache==1.3
cffi==1.10.0
...
To individually find the version number you can grep on this output on *NIX machines. 要单独查找版本号,您可以在* NIX机器上的此输出上进行grep。 For example:
例如:
$ pip freeze | grep PyMySQL
PyMySQL==0.7.11 On windows, you can use findstr instead of grep. PyMySQL == 0.7.11在Windows上,您可以使用findstr而不是grep。 For example:
例如:
PS C:\> pip freeze | findstr PyMySql
PyMySQL==0.7.11 PyMySQL == 0.7.11
If you want to know the version of a module within a Python script, you can use the __version__
attribute of the module to get it. 如果您想知道Python脚本中模块的版本,可以使用模块的
__version__
属性来获取它。 Note that not all modules come with a __version__
attribute. 请注意,并非所有模块都带有
__version__
属性。 For example, 例如,
>>> import pylint
>>> pylint.__version__
'1.7.1'
This answer is for Windows users.此答案适用于 Windows 用户。 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, you can simply do:
因此,您可以简单地执行以下操作:
In summary:总之:
conda list
(It will provide all the libraries along with version details.) (它将提供所有库以及版本详细信息。)
And:和:
pip show tensorflow
(It gives complete library details.) (它提供了完整的库详细信息。)
This works in Jupyter Notebook on Windows, too!这也适用于 Windows 上的Jupyter Notebook ! As long as Jupyter is launched from a Bash-compliant command line such as Git Bash ( Mingw-w64 ), the solutions given in many of the answers can be used in Jupyter Notebook on Windows systems with one tiny tweak.
只要 Jupyter 是从符合 Bash 的命令行启动的,例如Git Bash ( Mingw-w64 ),许多答案中给出的解决方案就可以在 Windows 系统上的 Jupyter Notebook 中使用,只需稍作调整。
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).我正在通过Anaconda安装 Python 运行 Windows 10 Pro,当我通过 Git Bash 启动 Jupyter 时,以下代码有效(但当我从 Anaconda 提示符启动时无效)。
The tweak: Add an exclamation mark ( !
) in front of pip
to make it !pip
.调整:在
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
A Python program to list all packages (you can copy it to file requirements.txt ):列出所有包的 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)
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
(See also How do I get the version of an installed module in Python programmatically? ) (另请参阅如何以编程方式在 Python 中获取已安装模块的版本? )
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 .我发现使用各种可用的工具(包括Jakub Kukul 的回答提到的最好的一个
pkg_resources
)非常不可靠,因为它们中的大多数并不涵盖所有情况。 For example例如
Since we needed a reliable way to get the version of any package, module or submodule, I ended up writing getversion .由于我们需要一种可靠的方法来获取任何包、模块或子模块的版本,因此我最终编写了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.有关详细信息,请参阅文档。
After scouring the Internet, trying to figure out how to ensure the version of a module I'm running (apparently python_is_horrible.__version__
isn't a thing in Python 2?) across operating systems and Python versions... literally none of these answers worked for my scenario...在搜索了互联网之后,试图弄清楚如何确保我正在运行的模块的版本(显然
python_is_horrible.__version__
不是 Python 2 中的东西?)跨操作系统和 Python 版本......实际上这些答案都没有为我的场景工作......
Then I thought about it a minute and realized the basics... after ~30 minutes of fails...然后我想了一分钟,意识到了基础......在失败了大约 30 分钟之后......
assumes the module is already installed and can be imported
假设模块已经安装并且可以导入
>>> import sys,sqlite3
>>> sys.modules.get("sqlite3").version
'2.6.0'
>>> ".".join(str(x) for x in sys.version_info[:3])
'3.7.2'
>>> import sys,sqlite3
>>> sys.modules.get("sqlite3").version
'2.6.0'
>>> ".".join(str(x) for x in sys.version_info[:3])
'2.7.11'
Literally that's it...字面意思就是这样...
Go to terminal like pycharm-terminal像 pycharm-terminal 一样转到终端
Now write py
or python
and hit Enter .现在编写
py
或python
并按Enter 。
Now you are inside python in the terminal you can try this way:现在您在终端的 python 中,您可以尝试这种方式:
# import <name_of_the_library>
import kivy
# So if the library has __version__ magic method, so this way will help you
kivy.__version__ # then hit Enter to see the version
# Output >> '2.1.0'
but if the above way not working for you can try this way to know information include the version of the library但如果上述方式不适合您可以尝试这种方式来了解信息包括库的版本
pip show module <HERE PUT THE NAME OF THE LIBRARY>
Example:例子:
pip show module pyperclip
Output:
Name: pyperclip
Version: 1.8.2
Summary: A cross-platform clipboard module for Python. (Only handles plain text for now.)
Home-page: https://github.com/asweigart/pyperclip
Author: Al Sweigart
Author-email: al@inventwithpython.com
License: BSD
Location: c:\c\kivymd\virt\lib\site-packages
Requires:
Required-by:
There is another way that could help you to show all the libraries and versions of them inside the project:还有另一种方法可以帮助您在项目中显示所有库和它们的版本:
pip freeze
# I used the above command in a terminal inside my project this is the output
certifi==2021.10.8
charset-normalizer==2.0.12
docutils==0.18.1
idna==3.3
Kivy==2.1.0
kivy-deps.angle==0.3.2
kivy-deps.glew==0.3.1
kivy-deps.sdl2==0.4.5
Kivy-Garden==0.1.5
kivymd @ file:///C:/c/kivymd/KivyMD
Pillow==9.1.0
Pygments==2.12.0
pyperclip==1.8.2
pypiwin32==223
pywin32==303
requests==2.27.1
urllib3==1.26.9
and sure you can try using the below command to show all libraries and their versions并确保您可以尝试使用以下命令显示所有库及其版本
pip list
Hope to Help anyone, Greetings希望能帮助到任何人,问候
To get a list of non-standard (pip) modules imported in the current module:要获取在当前模块中导入的非标准 (pip) 模块列表:
[{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?此代码是从本页上的解决方案和如何列出导入的模块?
And in case your production system is hardened beyond comprehension so it has neither pip
nor conda
, here is a Bash replacement for pip freeze
:如果您的生产系统变得难以理解,因此它既没有
pip
也没有conda
,这里是pip freeze
的 Bash 替代品:
ls /usr/local/lib/python3.8/dist-packages | grep info | awk -F "-" '{print $1"=="$2}' | sed 's/.dist//g'
(make sure you update your dist-packages
folder to your current python version and ignore inconsistent names, eg, underscores vs. dashes). (确保将
dist-packages
文件夹更新为当前的 python 版本并忽略不一致的名称,例如下划线与破折号)。
Sample printout:样本打印输出:
Flask==1.1.2
Flask_Caching==1.10.1
gunicorn==20.1.0
[..]
Here's a small Bash program to get the version of any package in your Python environment.这是一个小型 Bash 程序,用于获取 Python 环境中任何包的版本。 Just copy this to your
/usr/bin
and provide it with executable permissions:只需将其复制到您的
/usr/bin
并为其提供可执行权限:
#!/bin/bash
packageName=$1
python -c "import ${packageName} as package; print(package.__version__)"
Then you can just run it in the terminal, assuming you named the script py-check-version
:然后您可以在终端中运行它,假设您将脚本命名为
py-check-version
:
py-check-version whatever_package
For situations where field __version__
is not defined:对于未定义字段
__version__
的情况:
try:
from importlib import metadata
except ImportError:
import importlib_metadata as metadata # python<=3.7
metadata.version("package")
Alternatively, and like it was already mentioned:或者,就像已经提到的那样:
import pkg_resources
pkg_resources.get_distribution('package').version
Building on Jakub Kukul's answer I found a more reliable way to solve this problem.基于Jakub Kukul 的回答,我找到了一种更可靠的方法来解决这个问题。
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.该方法的主要问题是需要“按常规”安装软件包(并且不包括使用
pip install --user
),或者在 Python 初始化时位于系统 PATH 中。
To get around that you can use pkg_resources.find_distributions(path_to_search)
.要解决这个问题,您可以使用
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.如果
path_to_search
在系统 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 in the right direction.感谢 Jakub Kukul 指出了正确的方向。
I myself work in a heavily restricted server environment and unfortunately none of the solutions here are working for me.我自己在一个受到严格限制的服务器环境中工作,不幸的是,这里的解决方案都不适合我。 There may be no global solution that fits all, but I figured out a swift workaround by reading the terminal output of pip freeze within my script and storing the modules labels and versions in a dictionary.
可能没有适合所有人的全局解决方案,但我通过在我的脚本中读取 pip freeze 的终端输出并将模块标签和版本存储在字典中找到了一个快速的解决方法。
import os
os.system('pip freeze > tmpoutput')
with open('tmpoutput', 'r') as f:
modules_version = f.read()
module_dict = {item.split("==")[0]:item.split("==")[-1] for item in modules_versions.split("\n")}
Retrieve your module's versions through passing the module label key, eg:通过传递模块标签键来检索模块的版本,例如:
>> module_dict["seaborn"]
'0.9.0'
I had the same problem, I tried to uninstall both modules: serial
and pyserial
. 我遇到了同样的问题,我试图卸载这两个模块:
serial
和pyserial
。 Then I reinstalled pyserial
ONLY and it worked perfectly. 然后我重新安装
pyserial
ONLY它完美地工作。
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 the package version.它应该为您提供软件包版本。
You can simply use subprocess.getoutput(python3 --version)
:您可以简单地使用
subprocess.getoutput(python3 --version)
:
import subprocess as sp
print(sp.getoutput(python3 --version))
# Or however it suits your needs!
py3_version = sp.getoutput(python3 --version)
def check_version(name, version):...
check_version('python3', py3_version)
For more information and ways to do this without depending on the __version__
attribute:有关不依赖于
__version__
属性的更多信息和方法:
Assign output of os.system to a variable and prevent it from being displayed on the screen 将 os.system 的输出分配给一个变量并阻止它显示在屏幕上
You can also use subprocess.check_output()
which raises an error when the subprocess returns anything other than exit code 0:您还可以使用
subprocess.check_output()
当子进程返回退出代码 0 以外的任何内容时引发错误:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.