如何检查python模块的版本?

2024-03-29 09:41:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚安装了python模块:constructstatlib,使用setuptools如下:

# 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


Tags: 模块installtheto版本fordownloadeasy
3条回答

你可以试试

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

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

我建议使用pip in place of easy_install。使用pip,您可以使用

pip freeze

在大多数linux系统中,您可以通过管道将其传递到grep(或在Windows上为findstr)以查找您感兴趣的特定包的行:

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

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

对于单个模块,您可以尝试^{} attribute,但是有些模块没有它:

$ 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环境中。强烈建议查看pythonvirtual environment管理器,例如virtualenvwrapper

使用与setuptools库一起分发的pkg_resources模块。请注意,传递给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)。

相关问题 更多 >