【问题标题】:show reverse dependencies with pip?用 pip 显示反向依赖关系?
【发布时间】:2014-02-15 15:54:15
【问题描述】:

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

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

【问题讨论】:

标签: python dependencies pip


【解决方案1】:

可以使用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]

【讨论】:

    【解决方案2】:

    若要更新当前 (2019) 的答案,当 pip.get_installed_distributions() 不再存在时,请使用 pkg_resources(如 a comments 中所述):

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

    【讨论】:

      【解决方案3】:

      这对于使用 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
      

      【讨论】:

        【解决方案4】:

        我发现 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')
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-21
        • 2017-09-23
        • 2019-06-16
        • 1970-01-01
        • 1970-01-01
        • 2016-01-10
        • 2015-07-19
        • 2012-02-20
        相关资源
        最近更新 更多