You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pip install -r requirements.txt无法解析环境变量问题求助

问题原因

pip 不会自动解析 requirements.txt 文件中的 shell 环境变量语法(${VAR} 格式)。直接在命令行执行安装命令时,${GITLAB_TOKEN_USER} 和 ${GITLAB_TOKEN} 是由你的 shell(比如bash/zsh)先解析成实际值,再传递给 pip 的;但使用 pip install -r requirements.txt 时,pip 会直接读取文件内容,不会经过 shell 处理,导致变量无法展开,最终请求 GitLab 时携带的是未解析的变量字符串,自然触发 401 认证失败。

无需硬编码令牌的解决方案

以下几种方法都能避免硬编码令牌,同时正常安装私有包:

方法1:通过环境变量指定索引地址

在执行 pip install 前,先设置 PIP_INDEX_URL 环境变量,让 pip 自动使用这个索引地址:

# Linux/macOS 或 Windows Git Bash
export PIP_INDEX_URL="https://${GITLAB_TOKEN_USER}:${GITLAB_TOKEN}@gitlab.com/api/v4/projects/1234567/packages/pypi/simple"
pip install -r requirements.txt
:: Windows 命令提示符
set PIP_INDEX_URL=https://%GITLAB_TOKEN_USER%:%GITLAB_TOKEN%@gitlab.com/api/v4/projects/1234567/packages/pypi/simple
pip install -r requirements.txt

此时 requirements.txt 只需要保留包名即可,无需写 --index-url 行:

my-package-name

方法2:使用 pip 配置文件

创建 pip 的全局或用户级配置文件,将索引地址和环境变量写入其中,pip 会自动解析变量:

  • Linux/macOS:在 ~/.config/pip/pip.conf 中添加内容
  • Windows:在 %APPDATA%\pip\pip.ini 中添加内容

配置文件内容如下:

[global]
index-url = https://${GITLAB_TOKEN_USER}:${GITLAB_TOKEN}@gitlab.com/api/v4/projects/1234567/packages/pypi/simple

之后直接执行 pip install -r requirements.txt 即可,requirements.txt 只需包含包名。

方法3:用 shell 命令先替换变量再传递给 pip

借助 envsubst 工具(Linux/macOS 自带,Windows 可通过 Git Bash 或安装 GNU 工具链获取),先替换 requirements.txt 中的环境变量,再传给 pip:

cat requirements.txt | envsubst | pip install -r -

这种方法可以保留 requirements.txt 中的 --index-url 配置,同时让变量被正常解析。

内容的提问来源于stack exchange,提问作者Enzo Ramirez C.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 13:50:26