我使用setuptools安装了Python模块construct和statlib:

sudo apt-get install python-setuptools

sudo easy_install statlib
sudo easy_install construct

如何从命令行检查它们的版本?


当前回答

使用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。

其他回答

您可以简单地使用子流程。getoutput (python3——版本):

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)

有关更多信息和不依赖__version__属性的方法:

指定os的输出。系统的一个变量,并防止它显示在屏幕上

你也可以使用subprocess.check_output(),当子进程返回的不是退出码0时,它会引发一个错误:

subprocess—子进程管理

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)"

获取当前模块中导入的非标准(pip)模块列表:

[{pkg.key : pkg.version} for pkg in pip.get_installed_distributions() 
   if pkg.key in set(sys.modules) & set(globals())]

结果:

>>> 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'}]

注意:

这段代码从解决方案放在一起在这个页面和如何列出导入的模块?

我建议在终端中打开一个Python shell(在您感兴趣的Python版本中),导入库,并获取其__version__属性。

>>> import statlib
>>> statlib.__version__

>>> import construct
>>> contruct.__version__

注1:我们必须考虑Python版本。如果已经安装了不同版本的Python,则必须在感兴趣的Python版本中打开终端。例如,使用Python 3.8打开终端可以(肯定会)提供与使用Python 3.5或Python 2.7打开不同版本的库。

注意2:我们避免使用print函数,因为它的行为依赖于Python 2或Python 3。我们不需要它,终端将显示表达式的值。

前面的答案没有解决我的问题,但这段代码做到了:

import sys 
for name, module in sorted(sys.modules.items()): 
  if hasattr(module, '__version__'): 
    print name, module.__version__