如何使用setuptools dependency_links安装Git仓库最新master分支依赖?
嘿,这个问题我太熟了!之前踩过pip版本更新后dependency_links失效的坑,还折腾过Python2/3依赖区分的需求,下面给你一步步解决:
解决方法:用Git仓库master分支作为依赖(支持Python2/3区分)
一、先搞懂核心问题:dependency_links已被弃用
首先要敲黑板:从pip 19.0版本开始,dependency_links已经被官方弃用了,默认不会被处理——这大概率就是你的依赖被忽略的原因!现在推荐用PEP 508标准的直接依赖写法,完全不需要再用dependency_links字段。
二、针对Python2/3的不同依赖配置
根据你说的“依赖包针对Python2和3有不同版本”,我分两种常见场景给你写配置:
场景1:Python2用正式发布版,Python3用master分支
假设你的主包在Python2上依赖PyPI的正式版,Python3上依赖GitHub的最新master分支,直接在setup.py的install_requires里用环境标记区分,同时把Git分支的URL直接写进去:
from setuptools import setup setup( name="your-package-name", version="0.1.0", # 核心依赖配置:精准区分Python版本 install_requires=[ # Python2用PyPI上的正式稳定版 "target-dependency>=1.0.0; python_version < '3.0'", # Python3用GitHub的master分支,注意格式:包名@GitURL#egg=包名 "target-dependency@git+https://github.com/owner/repo.git@master#egg=target-dependency; python_version >= '3.0'" ], # 划重点:新版本pip不需要下面这行!仅旧版pip(<19.0)才需要保留 # dependency_links=[ # "git+https://github.com/owner/repo.git@master#egg=target-dependency" # ] )
场景2:Python2和3分别用该依赖的不同分支
如果Python2对应依赖的py2-compat分支,Python3对应master分支,写法类似:
install_requires=[ "target-dependency@git+https://github.com/owner/repo.git@py2-compat#egg=target-dependency; python_version < '3.0'", "target-dependency@git+https://github.com/owner/repo.git@master#egg=target-dependency; python_version >= '3.0'" ]
三、确保pip正确识别并安装依赖
1. 新版本pip(>=19.0)
直接用常规pip命令就行,PEP 508的写法会被自动识别:
# 本地安装你的包 pip install . # 或者从PyPI安装(如果你的包已经上传) pip install your-package-name
2. 旧版本pip(<19.0)
如果必须用旧版pip,得加上--process-dependency-links参数,同时保留setup.py里的dependency_links字段:
pip install . --process-dependency-links
四、常见坑点排查
如果还是出现依赖被忽略的情况,检查这几点:
- 包名必须完全一致:Git URL里
#egg=xxx的名字,要和install_requires里的依赖名完全匹配,大小写都不能错! - Git URL格式要对:公开仓库用
git+https://github.com/owner/repo.git@分支名#egg=包名,私有仓库换成git+ssh://git@github.com/owner/repo.git@分支名#egg=包名 - 确认pip版本:pip 20.0+完全不支持
dependency_links,必须改用PEP 508写法 - 虚拟环境检查:确保你操作的是目标虚拟环境,避免全局pip版本和虚拟环境内的不一致
内容的提问来源于stack exchange,提问作者BlandCorporation




