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

sudo apt-get install python-setuptools

sudo easy_install statlib
sudo easy_install construct

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


当前回答

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

其他回答

你可以试试

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

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

这是PEP 396推荐的方法。但是PEP从未被接受,并且一直被推迟。事实上,Python核心开发人员似乎越来越支持不包含__version__属性,例如在Remove importlib_metadata.version..

一个列出所有包的Python程序(你可以把它复制到file requirements.txt):

from pip._internal.utils.misc import get_installed_distributions
print_log = ''
for module in sorted(get_installed_distributions(), key=lambda x: x.key):
    print_log +=  module.key + '~=' + module.version  + '\n'
print(print_log)

输出如下所示:

asn1crypto~=0.24.0
attrs~=18.2.0
automat~=0.7.0
beautifulsoup4~=4.7.1
botocore~=1.12.98

使用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 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中用于过滤出版本并显示它。

首先将可执行文件python和pip添加到环境变量中。这样您就可以从命令提示符执行您的命令。然后简单地给出Python命令。

然后导入包:

import scrapy

然后打印版本名

print(scrapy.__version__)

这肯定有用。