在python

时间:2019-03-05 16:49:19

标签: python pip

我想获取特定程序包的依赖项。使用以下命令,我将获得完整的依赖关系树,其中显示了所有已安装的库。

  

pipdeptree --json-tree -p numpy

有没有一种方法可以仅获取树形式的程序包的依赖项

1 个答案:

答案 0 :(得分:2)

根据pipdeptree -h中的帮助,--json-tree选项将覆盖-p选项:

--json-tree       Display dependency tree as json which is nested the
                  same way as the plain text output printed by default.
                  This option overrides all other options (except
                  --json).

因此,不幸的是,看起来像显示单个包的树,因为通常无法使用json。仅使用-p选项而不使用--json-tree可以正常工作:

$ pipdeptree -p numpy
numpy==1.16.2

但是不幸的是,这只是常规输出。

当然,您总是可以通过将pipdeptree导入到脚本中来将其合并在一起:

import pipdeptree
import json

pkgs = pipdeptree.get_installed_distributions()
dist_index = pipdeptree.build_dist_index(pkgs)
tree = pipdeptree.construct_tree(dist_index)
json_tree = json.loads(pipdeptree.render_json_tree(tree, indent=0))
print([package for package in json_tree if package['package_name'] == 'numpy'][0])

输出

{'required_version': '1.16.2', 'dependencies': [], 'package_name': 'numpy', 'installed_version': '1.16.2', 'key': 'numpy'}

如果您想尝试如下操作,则源代码在这里:https://github.com/naiquevin/pipdeptree/blob/master/pipdeptree.py

相关问题