首页 > 解决方案 > 查找 pip 包:pkg_resources 指定自定义目标目录

问题描述

有没有办法为 pkg_resources 指定一个自定义目标目录来列出 pip 包?我希望能够使用已经使用自定义目标目录提供的--target类似东西来查找已安装在自pkg_resources.require()定义目标目录中的包。

我不想要的是使用:

我很感激这方面的任何帮助。

标签: pythonpython-2.7pipsetuptoolspkg-resources

解决方案


更新

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)]

推荐阅读