我使用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
如何从命令行检查它们的版本?
当前回答
在Python 3中用括号括起来的print:
>>> import celery
>>> print(celery.__version__)
3.1.14
其他回答
模块。__version__是一个很好的尝试,但它并不总是有效。
如果你不想退出,并且你正在使用pip 8或9,你仍然可以使用pip.get_installed_distribution()从Python内部获取版本:
这里的解决方案适用于pip 8和9,但在pip 10中,该函数已从pip中移动。get_installed_distribution到pip._internal.utils.misc。get_installed_distribution显式地指出它不供外部使用。如果您正在使用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', ...]
使用pip而不是easy_install。
使用pip,通过以下方式列出所有已安装的软件包及其版本:
pip freeze
在大多数Linux系统上,您可以将其输送到grep(或Windows上的findstr),以查找您感兴趣的特定包的行。
Linux:
pip freeze | grep lxml
lxml = = 2.3
窗口:
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__)"
回溯(最近一次调用): 文件"<string>",第1行,在<模块> 'module'对象没有'version'属性
最后,由于您的问题中的命令带有sudo前缀,似乎您正在安装到全局python环境。我强烈建议研究一下Python虚拟环境管理器,例如virtualenvwrapper。
你可以先安装这样的包,然后检查它的版本:
pip install package
import package
print(package.__version__)
它会给你一个打包的版本。
这工作在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
(请参见如何以编程方式获取Python中已安装模块的版本?)
我发现使用各种可用的工具(包括Jakub Kukul回答中提到的最好的pkg_resources)是非常不可靠的,因为大多数工具都不能覆盖所有情况。例如
内置模块 模块没有安装,只是添加到python路径(例如,通过IDE) 同一模块可用的两个版本(python路径中的一个取代已安装的版本)
因为我们需要一种可靠的方法来获取任何包、模块或子模块的版本,所以我最终编写了getversion。使用起来很简单:
from getversion import get_module_version
import foo
version, details = get_module_version(foo)
详细信息请参见文档。