我使用setuptools安装了Python模块construct和statlib:
sudo apt-get install python-setuptools
sudo easy_install statlib
sudo easy_install construct
如何从命令行检查它们的版本?
我使用setuptools安装了Python模块construct和statlib:
sudo apt-get install python-setuptools
sudo easy_install statlib
sudo easy_install construct
如何从命令行检查它们的版本?
当前回答
下面是一个小Bash程序,用于获取Python环境中任何包的版本。只需复制到你的/usr/bin,并为其提供可执行权限:
#!/bin/bash
packageName=$1
python -c "import ${packageName} as package; print(package.__version__)"
然后你可以在终端中运行它,假设你将脚本命名为py-check-version:
py-check-version whatever_package
其他回答
你可以试试
>>> import statlib
>>> print statlib.__version__
>>> import construct
>>> print contruct.__version__
这是PEP 396推荐的方法。但是PEP从未被接受,并且一直被推迟。事实上,Python核心开发人员似乎越来越支持不包含__version__属性,例如在Remove importlib_metadata.version..
首先将可执行文件python和pip添加到环境变量中。这样您就可以从命令提示符执行您的命令。然后简单地给出Python命令。
然后导入包:
import scrapy
然后打印版本名
print(scrapy.__version__)
这肯定有用。
Python >= 3.8:
如果您使用的是Python >= 3.8,则可以使用内置库中的模块。要检查包的版本(在这个例子中),运行:
>>> from importlib.metadata import version
>>> version('construct')
'4.3.1'
Python < 3.8:
使用随setuptools库分发的pkg_resources模块。注意,传递给get_distribution方法的字符串应该对应于PyPI条目。
>>> import pkg_resources
>>> pkg_resources.get_distribution('construct').version
'2.5.2'
边注:
请注意,传递给get_distribution方法的字符串应该是在PyPI中注册的包名,而不是您试图导入的模块名。不幸的是,它们并不总是相同的(例如,你安装了memcached,但导入了memcache)。 如果你想从命令行应用这个解决方案,你可以这样做:
python -c \
"import pkg_resources; print(pkg_resources.get_distribution('construct').version)"
(请参见如何以编程方式获取Python中已安装模块的版本?)
我发现使用各种可用的工具(包括Jakub Kukul回答中提到的最好的pkg_resources)是非常不可靠的,因为大多数工具都不能覆盖所有情况。例如
内置模块 模块没有安装,只是添加到python路径(例如,通过IDE) 同一模块可用的两个版本(python路径中的一个取代已安装的版本)
因为我们需要一种可靠的方法来获取任何包、模块或子模块的版本,所以我最终编写了getversion。使用起来很简单:
from getversion import get_module_version
import foo
version, details = get_module_version(foo)
详细信息请参见文档。
这工作在Jupyter笔记本上的Windows,太!只要Jupyter是从兼容Bash的命令行(如Git Bash (Mingw-w64))启动的,许多答案中给出的解决方案都可以在Windows系统上的Jupyter Notebook中使用,只需稍加调整。
我运行的是通过Anaconda安装Python的Windows 10 Pro,当我通过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