python - 查找 pip 包:pkg_resources 指定自定义目标目录
问题描述
有没有办法为 pkg_resources 指定一个自定义目标目录来列出 pip 包?我希望能够使用已经使用自定义目标目录提供的--target
类似东西来查找已安装在自pkg_resources.require()
定义目标目录中的包。
我不想要的是使用:
setuptools.find_packages
因为它只使用sys.path
setuptools.PEP420PackageFinder.find
- 通过遍历目录名称和文件来查找包也没有帮助,因为我需要一种更通用的方法来查找包命名空间。
我很感激这方面的任何帮助。
解决方案
更新
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)]
推荐阅读
- javascript - 如何同时旋转和缩放图像?
- c - 如何将字符串压入堆栈?
- c++ - 如何使用 GPU 对点云进行坐标变换?
- c# - MVC 绑定到实体调用区域
- jestjs - 使用 test.each 断言失败的笑话日志消息
- powerbi - 使用 Power BI (DirectQuery) 计算每日收入和预算之间的差异
- azure-data-explorer - Azure 数据资源管理器 (Kusto) 覆盖 creationTime
- javascript - 服务器端 VS 数据传输中的自动完成
- xml - 使用 refcursor 作为参数类型时的 SOA Gateway xml 输出
- arrays - 用数组填充列表框