pip镜像源配置

pip非持久化换源,持久化换源(修改配置文件和命令两种方式)。以及使用阿里源安装pytorch。
machine-learning
softwares
Author

Aroma

Published

November 14, 2025

Modified

November 14, 2025

最近尝试从cuda docker image配置项目环境,然后上传到服务端训练。这要求从python安装开始配置深度学习环境。由于需要用脚本配置,并软件镜像源加速,我认为是难得的“从头配置”经验。

深度学习常用的软件包括:python, pip, conda
本文记录pip的换源方法,尤其是针对pytorch换源。

pip非持久化换源

利用-i(--index-url)参数指定源,例如安装包package

pip install package -i https://mirrors.aliyun.com/pypi/simple/ 

用此方法从requirements.txt安装依赖:

pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/

pip默认支持https源,如果必须使用http源,可使用--trusted-host避免SSL证书检查(当然也增加了中间人攻击风险):

pip install package -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com

你还可以使用-f(--find-links)参数指定源,可以把文件路径、指向tar或wheel的url、git等传给pip。给它的参数不需要遵守PEP 503-i只接收遵守该规范的)。比较常用的情况:从本地安装软件包,用-find-links yourDir--no-index

pip持久化换源

通过配置文件

linux下,修改~/.pip/pip.conf(没有则创建),添加镜像源(每行一个)。

通过命令添加

全局添加镜像源:

pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/

删除所有镜像源:

pip config unset global.index-url

类似地,可以修改其他配置

pip config set global.trusted-host mirrors.aliyun.com 
pip config set global.find-links file:///home/user/somewheel.whl

和删除配置

pip config unset global.trusted-host
pip config unset global.find-links

社区一键配置的shell

改pip下载源为国内(我没有尝试)

pip用镜像源下载pytorch

pytorch建议的pip下载命令类似于

pip install torch==2.5.0 torchvision==0.20.0 torchaudio==2.5.0 --index-url https://download.pytorch.org/whl/cu124

实际上就是指定index-url,因此上面的镜像源不会被使用。而常用的镜像源只提供pypi镜像(只包含cpu版的)。
使用阿里源能解决这个问题,使用前面提过的-f设定源:

pip install torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 -f https://mirrors.aliyun.com/pytorch-wheels/cu118

References