使现代化
引入Python 3.8
importlib.metadata
,一个用于查询取代
pkg_resources
.示例用法:
In [1]: from importlib import metadata
In [2]: dists = metadata.distributions(path=['my_target_dir'])
In [3]: list(f"{d.metadata['Name']}=={d.metadata['Version']}" for d in dists)
Out[22]:
['pip==20.0.2',
'ipython==7.13.0',
...
]
对于Python 2.7和Python>=3.5,有一个叫
importlib-metadata
:
$ pip install importlib-metadata
原始答案
这个
pkg_resources.find_distributions
功能(记录在
Getting or Creating Distributions
)接受目标目录以在中搜索包。示例:
$ ls -l my_target_dir/
total 36
drwxr-xr-x 2 hoefling hoefling 4096 May 17 13:29 __pycache__
-rw-r--r-- 1 hoefling hoefling 126 May 17 13:29 easy_install.py
drwxr-xr-x 5 hoefling hoefling 4096 May 17 13:29 pip
drwxr-xr-x 2 hoefling hoefling 4096 May 17 13:29 pip-10.0.1.dist-info
drwxr-xr-x 5 hoefling hoefling 4096 May 17 13:29 pkg_resources
drwxr-xr-x 6 hoefling hoefling 4096 May 17 13:29 setuptools
drwxr-xr-x 2 hoefling hoefling 4096 May 17 13:29 setuptools-39.1.0.dist-info
drwxr-xr-x 5 hoefling hoefling 4096 May 17 13:29 wheel
drwxr-xr-x 2 hoefling hoefling 4096 May 17 13:29 wheel-0.31.1.dist-info
正在扫描
my_target_dir
具有
pkg\U资源。查找分布
收益率:
In [2]: list(pkg_resources.find_distributions('my_target_dir'))
Out[2]:
[wheel 0.31.1 (/data/gentoo64/tmp/so-50380624/my_target_dir),
setuptools 39.1.0 (/data/gentoo64/tmp/so-50380624/my_target_dir),
pip 10.0.1 (/data/gentoo64/tmp/so-50380624/my_target_dir)]