如何在Python中查找已安装库的版本?

How to find the version of installed library in Python?

如何找到我系统上安装的 clang 版本。

Link 到 clang 库:(click!)

我想要这样的功能:

if libclang.version < 3.4:  
    print('Clang version not supported.')

或其他一些逻辑,以便我可以找到 clang 的版本。

clang 模块中没有 __version__ 属性。所以我做不到

if libclang.__version__ < 3.4
    print('Clang version not supported.')

如果无法直接获取任何包的版本,可以执行

pip freeze | grep clang

在您的脚本中,为了执行此脚本,您可以使用 python 的子进程模块,如下所述:

>>> import subprocess
>>> p = subprocess.Popen(["pip", "freeze", "|", "grep", "clang"], stdout=subprocess.PIPE)
>>> p.communicate()[0].splitlines()
这将 return 所有软件包及其软件包一起安装,您可以在那里安装 clang 版本。
from pkg_resources import get_distribution

if get_distribution('libclang-py3').version != '3.4.0':
    logging.error('clang version not supported')

get_distribution('pkg_name').version 将 return 安装包的版本,但这可能并非在所有情况下都有效。

获取所有已安装库的最简单方法是 >>pip list