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

sudo apt-get install python-setuptools

sudo easy_install statlib
sudo easy_install construct

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


当前回答

您可以简单地使用子流程。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程序(你可以把它复制到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

您可以简单地使用子流程。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—子进程管理

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

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 install package
import package
print(package.__version__)

它会给你一个打包的版本。