国内Python包镜像地址如下:
- 清华:https://pypi.tuna.tsinghua.edu.cn/simple/
- 阿里云:https://mirrors.aliyun.com/pypi/simple/
- 中国科技大学:https://pypi.mirrors.ustc.edu.cn/simple/
- 华为云:https://repo.huaweicloud.com/repository/pypi/simple/
- 腾讯云:https://mirrors.cloud.tencent.com/pypi/simple/
比如想把 pip 安装时的默认源设为清华源,从而提升国内的下载速度,可按下面的方法对 pip 进行配置:
一、单次安装时指定清华源
在使用 pip 执行安装命令时,借助 -i
参数就能临时指定清华源,示例如下:
pip install 包名 -i https://pypi.tuna.tsinghua.edu.cn/simple
二、永久修改默认源(推荐做法)
1. 配置文件法(推荐)
创建或编辑 pip 的配置文件,具体操作如下:
-
Windows 系统:
先在C:\Users\你的用户名\pip\
路径下创建pip.ini
文件,若该路径不存在则先创建相应文件夹,然后在pip.ini
中写入以下内容:
[global] index-url = https://pypi.tuna.tsinghua.edu.cn/simple[install] trusted-host = pypi.tuna.tsinghua.edu.cn
-
macOS/Linux 系统:
编辑~/.pip/pip.conf
文件(若文件不存在则创建),写入如下内容:[global] index-url = https://pypi.tuna.tsinghua.edu.cn/simple[install] trusted-host = pypi.tuna.tsinghua.edu.cn
2. 命令行快速配置
通过命令直接生成配置文件,以 macOS/Linux 系统为例:
mkdir -p ~/.pip
cat > ~/.pip/pip.conf << EOF
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = pypi.tuna.tsinghua.edu.cn
EOF
三、验证配置是否成功
执行以下命令安装某个包,观察输出信息:
pip install requests
若输出中包含类似 Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
的内容,就表明配置已成功生效。
四、其他常见国内镜像源
除了清华源,国内还有一些其他常用的镜像源,你也可以根据自身需求进行切换:
- 阿里云:
https://mirrors.aliyun.com/pypi/simple/
- 中国科技大学:
https://pypi.mirrors.ustc.edu.cn/simple/
- 豆瓣:
https://pypi.doubanio.com/simple/
若要切换为其他镜像源,只需在配置文件里修改 index-url
字段即可。
五、注意事项
- 虚拟环境:上述配置是全局生效的。如果使用了虚拟环境,且该虚拟环境有独立的 pip 配置,就需要单独进行设置。
- 临时切换:当清华源出现问题时,可通过
-i
参数临时使用其他镜像源。 - HTTPS 验证:添加
trusted-host
是为了信任清华源的 HTTPS 证书,防止出现安全提示。