更新
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 或 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_resources.find_distributions
:
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)]