如何在pyproject.toml中为依赖配置备选下载URL?
能否在pyproject.toml中为pip指定多个包查找URL?
首先明确:pip的依赖声明语法不支持直接在dependencies字段里用OR这种多源备选的写法,你期望的那种格式无法被pip识别。针对你需要在两个隔离企业网络用同一份配置拉取依赖的需求,有以下几种可行方案:
方案1:用环境变量动态注入仓库URL
在pyproject.toml里通过环境变量占位,让不同环境自动加载对应仓库地址:
[project] name = 'my_project' dependencies = [ 'library_package@{env:LIBRARY_PACKAGE_REPO}' ]
在网络A的机器上,执行安装前先设置环境变量:
export LIBRARY_PACKAGE_REPO=git+https://bitbucket-a.example.com/path/to/repo.git pip install .
在网络B的机器上则设置另一个地址:
export LIBRARY_PACKAGE_REPO=git+https://bitbucket-b.example.com/path/to/repo.git pip install .
这种方式只需要维护一份配置文件,通过环境变量适配不同网络环境。
方案2:安装时自动尝试备选仓库
如果不想依赖环境变量,可以写一个简单的安装脚本,让pip先尝试第一个仓库,失败后自动切换到第二个:
# 尝试从网络A的仓库安装,失败则切换到网络B pip install . library_package@git+https://bitbucket-a.example.com/path/to/repo.git || pip install . library_package@git+https://bitbucket-b.example.com/path/to/repo.git
这种方式不需要修改pyproject.toml,完全通过安装命令的逻辑来适配不同网络。
注意事项
- 不要使用已被弃用的
dependency-links字段,新版pip不再支持该特性。 - 确保两个Bitbucket仓库里的
library_package版本一致,避免安装时出现版本不一致的问题。
内容的提问来源于stack exchange,提问作者Caleb
相关产品推荐
相关产品推荐

