我使用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—子进程管理

其他回答

使用dir()来找出模块是否有__version__属性。

>>> import selenium
>>> dir(selenium)
['__builtins__', '__doc__', '__file__', '__name__',
 '__package__', '__path__', '__version__']
>>> selenium.__version__
'3.141.0'
>>> selenium.__path__
['/venv/local/lib/python2.7/site-packages/selenium']

模块。__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', ...]

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

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

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

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