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

sudo apt-get install python-setuptools

sudo easy_install statlib
sudo easy_install construct

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


当前回答

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

其他回答

模块。__version__是一个很好的尝试,但它并不总是有效。

如果你不想退出,并且你正在使用pip 8或9,你仍然可以使用pip.get_installed_distribution()从Python内部获取版本:

这里的解决方案适用于pip 8和9,但在pip 10中,该函数已从pip中移动。get_installed_distribution到pip._internal.utils.misc。get_installed_distribution显式地指出它不供外部使用。如果您正在使用pip 10+,那么依赖它不是一个好主意。

import pip

pip.get_installed_distributions()  # -> [distribute 0.6.16 (...), ...]

[
    pkg.key + ': ' + pkg.version
    for pkg in pip.get_installed_distributions()
    if pkg.key in ['setuptools', 'statlib', 'construct']
] # -> nicely filtered list of ['setuptools: 3.3', ...]

对于未定义字段__version__的情况:

try:
    from importlib import metadata
except ImportError:
    import importlib_metadata as metadata # python<=3.7

metadata.version("package")

或者,就像之前提到的那样:

import pkg_resources
pkg_resources.get_distribution('package').version

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

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

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

下面是一个小Bash程序,用于获取Python环境中任何包的版本。只需复制到你的/usr/bin,并为其提供可执行权限:

#!/bin/bash
packageName=$1

python -c "import ${packageName} as package; print(package.__version__)"

然后你可以在终端中运行它,假设你将脚本命名为py-check-version:

py-check-version whatever_package