如何让pip install跳过已存在包以加速安装过程?
解决pip重复安装已存在包的提速方案
这问题我太有共鸣了——每次执行pip install -r requirements.txt -t folder时,明明包已经存在且是最新版本,pip还要反复收集包信息、跑setup.py,真的很浪费时间。给你几个实用的办法,帮你跳过这些没必要的步骤:
1. 用--upgrade-strategy only-if-needed减少不必要的检查
pip默认的升级策略是eager——哪怕当前包版本完全符合requirements里的要求,它还是会去检查所有依赖的最新版本。换成only-if-needed策略后,pip只会在已安装版本不满足要求时才进行处理:
pip install --upgrade-strategy only-if-needed -r requirements.txt -t folder
这个参数直接改变pip的处理逻辑,能大幅减少对已达标包的无用操作。
2. 用--exists-action i直接跳过已存在的包
如果你的需求更简单——只要包已经在目标目录里,不管版本(当然你得确保版本是对的),就直接跳过安装,那可以用--exists-action i参数:
pip install --exists-action i -r requirements.txt -t folder
这里的i代表ignore,pip碰到已存在的包时会直接跳过,连版本检查都省了,速度会更快。
3. 写个前置检查脚本(极致提速)
如果你的环境非常稳定,大部分时候都不需要修改依赖,那可以写个小脚本先检查哪些包缺失或版本不达标,只安装需要更新的部分:
import pkg_resources import subprocess import sys requirements_path = "requirements.txt" target_folder = "folder" # 将目标目录加入Python路径,让脚本能检测里面的包 sys.path.insert(0, target_folder) # 收集需要安装/更新的包 needs_install = [] with open(requirements_path, "r") as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue try: # 检查当前目录下的包是否满足要求 pkg_resources.require(line) except (pkg_resources.DistributionNotFound, pkg_resources.VersionConflict): needs_install.append(line) if needs_install: print(f"Installing/updating: {', '.join(needs_install)}") subprocess.run([ sys.executable, "-m", "pip", "install", "-t", target_folder, *needs_install ], check=True) else: print("All packages are up-to-date, skipping installation.")
把这个脚本放在和requirements.txt同目录下,每次运行脚本而不是直接跑pip,它会帮你过滤掉所有已经符合要求的包,只处理真正需要的部分,效率拉满。
内容的提问来源于stack exchange,提问作者red888
相关产品推荐
相关产品推荐

