setup.py配置git仓库依赖到install_requires无法识别已安装包问题
根本原因
这是pip处理PEP 508规范中直接URL依赖的默认逻辑:就算添加了#egg后缀,pip也不会默认将本地已安装的包和URL来源的包做等价匹配,因为pip无法确认本地安装的版本和Git仓库中的代码版本是否一致,所以每次安装都会重新拉取Git仓库代码。
解决方案
- 方案1:给依赖添加版本约束
在依赖声明中加上明确的版本范围后,pip会先检查本地是否存在符合版本要求的已安装包,匹配成功就会跳过拉取:
setup( name="setuprequires", version="0.1", packages=["setuprequires"], install_requires=[ r"hello-world>=0.1 @ git+ssh://git@github.com/hello/hello-world.git#egg=hello-world" ], )
注意:需要确保Git仓库中hello-world包的配置文件(setup.py/pyproject.toml)里声明的版本号和你写的版本约束匹配,同时本地已安装的hello-world版本也符合约束要求,才能触发跳过逻辑。
- 方案2:拆分依赖声明与源配置
如果不想把Git地址硬编码在install_requires里,可以把依赖声明仅保留包名和版本约束,安装时按需指定源:
- 修改setup.py中的依赖配置:
install_requires=["hello-world>=0.1"]
- 首次安装需要拉取Git版本时,执行:
pip install -e . --find-links git+ssh://git@github.com/hello/hello-world.git#egg=hello-world
后续再次执行安装时,只要本地有符合版本要求的包,直接执行pip install -e .就不会额外拉取。
- 方案3:设为可选额外依赖
如果希望默认不强制拉取Git版本的依赖,仅当用户需要时才拉取,可以把该依赖设为额外依赖:
setup( name="setuprequires", version="0.1", packages=["setuprequires"], install_requires=[], extras_require={ "git_deps": ["hello-world @ git+ssh://git@github.com/hello/hello-world.git#egg=hello-world"] } )
普通安装执行pip install -e .不会处理该依赖,需要拉取Git版本时执行pip install -e .[git_deps]即可。
内容的提问来源于stack exchange,提问作者Betterthan Kwora
相关产品推荐
相关产品推荐

