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

sudo apt-get install python-setuptools

sudo easy_install statlib
sudo easy_install construct

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


当前回答

根据Jakub Kukul的回答,我找到了一个更可靠的方法来解决这个问题。

这种方法的主要问题是要求包按“常规”安装(不包括使用pip install——user),或者在Python初始化时位于系统PATH中。

要解决这个问题,可以使用pkg_resources. find_distributors (path_to_search)。如果path_to_search在系统PATH中,它基本上会搜索可导入的分布。

我们可以像这样遍历这个生成器:

avail_modules = {}
distros = pkg_resources.find_distributions(path_to_search)
for d in distros:
    avail_modules[d.key] = d.version

这将返回一个以模块为键,其版本为值的字典。这种方法可以扩展到比版本号更多的版本。

感谢Jakub Kukul指出了正确的方向。

其他回答

使用pip show查找版本!

# In order to get the package version, execute the below command
pip show YOUR_PACKAGE_NAME | grep Version

您可以使用pip show YOUR_PACKAGE_NAME -它会提供包的所有细节。这也适用于Windows。

grep Version在Linux中用于过滤出版本并显示它。

假设我们使用的是Jupyter Notebook(如果使用的是Terminal,去掉感叹号):

如果软件包(例如xgboost)与pip一起安装: 皮普秀xgboost !pip freeze | grep xgboost !pip list | grep xgboost 如果这个包(例如caffe)是用Conda安装的: conda list caffe

在Python 3中用括号括起来的print:

>>> import celery
>>> print(celery.__version__)
3.1.14

我建议在终端中打开一个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。我们不需要它,终端将显示表达式的值。

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