如何检查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


问题答案:

我建议使用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