使用pip显示反向依赖关系?

25

是否可以使用 pip 显示反向依赖关系?

我想知道哪个包需要 foo 包,以及该包需要哪个版本的 foo 包。


相关链接:https://github.com/nvie/pip-tools - guettli
4个回答

17

更新答案到当前时间(2019年),当pip.get_installed_distributions()不再存在时,请使用pkg_resources(如在评论中提到的):

import pkg_resources
import sys

def find_reverse_deps(package_name):
    return [
        pkg.project_name for pkg in pkg_resources.WorkingSet()
        if package_name in {req.project_name for req in pkg.requires()}
    ]

if __name__ == '__main__':
    print(find_reverse_deps(sys.argv[1]))

14

我认为Alexander的回答非常完美,只是复制/粘贴有些困难。这里是一份已经准备好可以直接粘贴的相同内容:

import pip
def rdeps(package_name):
    return [pkg.project_name
            for pkg in pip.get_installed_distributions()
            if package_name in [requirement.project_name
                                for requirement in pkg.requires()]]

rdeps('some-package-name')

6
记录一下,pip 没有公开的 API。随着 pip 10 的推出,本答案将无效。请改用 setuptools 中的 pkg_resources - Alex Grönholm
1
@AlexGrönholm的评论参考链接:https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program - David P

10

使用pip的Python API,已经安装的软件包是可以实现这一点的。有一个pip.get_installed_distributions函数,可以给出一个当前已安装的所有第三方软件包列表。

# rev_deps.py
import pip
import sys

def find_reverse_deps(package_name):
    return [
        pkg.project_name for pkg in pip.get_installed_distributions()
        if package_name in {req.project_name for req in pkg.requires()}
    ]

if __name__ == '__main__':
    print find_reverse_deps(sys.argv[1])

此脚本将输出需要指定软件包的包列表:

$python rev_deps.py requests

7

可以使用 pipdeptree 包。要列出已安装的 cffi 包的反向依赖项:

$ pipdeptree -p cffi -r
cffi==1.14.0
  - cryptography==2.9 [requires: cffi>=1.8,!=1.11.3]
    - social-auth-core==3.3.3 [requires: cryptography>=1.4]
      - python-social-auth==0.3.6 [requires: social-auth-core]
      - social-auth-app-django==2.1.0 [requires: social-auth-core>=1.2.0]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接