代码之家  ›  专栏  ›  技术社区  ›  hiradyazdan

查找pip包:pkg\u资源指定自定义目标目录

  •  1
  • hiradyazdan  · 技术社区  · 8 年前

    有没有办法为pkg\U资源指定一个自定义目标目录来列出pip包?我希望能够使用查找已安装在自定义目标目录中的程序包 --target 通过类似的方式 pkg_resources.require() 已提供自定义目标目录的。

    我不想使用:

    • setuptools.find_packages 因为它只使用 sys.path
    • setuptools.PEP420PackageFinder.find
    • 通过遍历目录名和文件来查找包也没有什么帮助,因为我需要一种更通用的方法来查找包名称空间。

    我很感谢你在这方面的帮助。

    1 回复  |  直到 8 年前
        1
  •  2
  •   hoefling    5 年前

    使现代化

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