在python中获取特定包的依赖树

2024-05-13 14:47:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

pipdeptree --json-tree -p numpy

只有以树的形式获取依赖关系


Tags: 命令numpyjsontree关系形式pipdeptree
1条回答
网友
1楼 · 发布于 2024-05-13 14:47:13

根据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可以按预期工作:

^{pr2}$

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

当然,您可以通过将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

相关问题 更多 >