获取python中特定包的依赖关系树

获取python中特定包的依赖关系树,python,pip,Python,Pip,我想获取特定包的依赖项。使用下面的命令,我得到显示所有已安装库的完整依赖关系树 pipdeptree--json树-p numpy 是否有方法仅获取树形包的依赖项根据pipdeptree-h中的帮助,--json tree选项覆盖-p选项: --json-tree Display dependency tree as json which is nested the same way as the plain text output printed

我想获取特定包的依赖项。使用下面的命令,我得到显示所有已安装库的完整依赖关系树

pipdeptree--json树-p numpy


是否有方法仅获取树形包的依赖项根据
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树
可以正常工作:

$ 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'}

如果您想尝试这样的操作,源代码就在这里:

谢谢!甚至我也想过要这样做,但是如果我们要寻找大量的包版本,那么在树中查找包并获取依赖项会花费很多时间。