如何查找曾安装指定Python包的来源依赖包?
注意:本问题并非关于当前依赖项,曾被误标记为其他问题的重复项。
问题背景
检查已安装Python包的更新时,常会碰到一些孤立包——推测它们是某个已安装包旧版本的依赖,但只有当这些遗留包推出新版本时,才会被偶然发现。
希望实现以下任一目标:
- 找出曾安装当前无依赖关系的指定包的来源包;
- 找出已安装的哪些包在更新后不再依赖其他包?
这么做的目的是,能够及时卸载不再被需要的无用包。
实际案例
我从未手动安装过ujson,但pip list --outdated显示它有新版本可用。执行pip show ujson后得到如下结果:
Name: ujson Version: 5.10.0 Summary: Ultra fast JSON encoder and decoder for Python Home-page: https://github.com/ultrajson/ultrajson Author: Jonas Tarnstrom Author-email: License: Location: C:\python\Lib\site-packages Requires: Required-by:
我可以卸载它,但不清楚还有哪些类似的遗留包可以移除。
模拟示例(帮助明确问题)
假设数月前我安装了bigpackagewithdependencies,该包当时有两个依赖项smallpackageIamnotaware和othersmallpackageIdontcarebutitdoesthejob,因此这些包会随主包一同安装。安装时执行pip freeze会得到如下结果(但我当时并未执行该命令):
bigpackagewithdependencies==42.0.0 smallpackageIamnotaware==1.0.1 othersmallpackageIdontcarebutitdoesthejob==1.0.0
之后,bigpackagewithdependencies更新到43.0.0版本,依赖项替换为mediumkillerpackage。此时仅更新主包后,执行pip freeze结果为:
bigpackagewithdependencies==43.0.0 smallpackageIamnotaware==1.0.1 othersmallpackageIdontcarebutitdoesthejob==1.0.0 mediumkillerpackage==3.14.159
当smallpackageIamnotaware推出2.0.0版本时,它会出现在pip list --outdated的结果中。由于我从未显式安装过它,执行pip list --not-required得到:
Package Version ---------------------- --------- bigpackagewithdependencies 43.0.0 smallpackageIamnotaware 1.0.1 othersmallpackageIdontcarebutitdoesthejob 1.0.0
此时我能确定smallpackageIamnotaware曾被某个包依赖但现在已无用,于是卸载了它。而othersmallpackageIdontcarebutitdoesthejob同样不再被任何包依赖,执行pip show会得到和ujson类似的结果(无依赖项,也不被其他包依赖)。
当前执行pip show bigpackagewithdependencies的结果为:
Name: bigpackagewithdependencies Version: 43.0.0 Summary: Just a big package that changes its dependencies from time to time (....) Location: C:\python\Lib\site-packages Requires: mediumkillerpackage Required-by:
核心疑问
通过smallpackageIamnotaware或othersmallpackageIdontcarebutitdoesthejob这类遗留包,是否有办法找出曾依赖它们的包及其对应版本?(示例中答案是bigpackagewithdependencies的42.0.0版本)
内容的提问来源于stack exchange,提问作者José Henrique Melman

