🇨🇳 中文

PIP国内镜像源

加速Python包安装,解决下载缓慢问题

国内镜像源介绍

由于网络原因,从PyPI官方源下载Python包可能会非常缓慢。使用国内镜像源可以显著提升下载速度,提高开发效率。

为什么需要镜像源?

  • 下载速度慢 - 官方源位于国外,国内访问速度受限
  • 连接不稳定 - 国际网络波动可能导致下载中断
  • 提高效率 - 加速开发环境和生产环境的部署

推荐镜像源列表

镜像名称 镜像地址 速度 操作
清华大学 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 快速
华为云 https://repo.huaweicloud.com/repository/pypi/simple 快速
腾讯云 https://mirrors.cloud.tencent.com/pypi/simple 快速

镜像源配置教程

以下三种方法可以配置PIP使用国内镜像源,推荐使用方法一(永久配置)

1

永久配置(推荐)

创建或修改pip配置文件,永久使用国内镜像源

pip.ini 配置文件内容(Windows)

# 将以下内容保存到:C:\Users\你的用户名\pip\pip.ini
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
trusted-host = pypi.tuna.tsinghua.edu.cn

# 其他可选配置
timeout = 600
retries = 5

pip.conf 配置文件内容(Linux/macOS)

# 将以下内容保存到:~/.pip/pip.conf
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
trusted-host = pypi.tuna.tsinghua.edu.cn

# 其他可选配置
timeout = 600
retries = 5
2

临时使用

在pip install命令后添加镜像源参数

install package-name -i https://pypi.tuna.tsinghua.edu.cn/simple

例如安装requests包:

install requests -i https://pypi.tuna.tsinghua.edu.cn/simple
3

环境变量配置

通过设置环境变量永久使用镜像源

Windows系统:

# 设置环境变量
setx PIP_INDEX_URL "https://pypi.tuna.tsinghua.edu.cn/simple"

Linux/macOS系统:

# 添加到 ~/.bashrc 或 ~/.zshrc
export PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
# 使配置生效
source ~/.bashrc
  • 常见问题
  • 验证配置
  • 高级配置

为什么配置后下载速度还是很慢?

可能原因:

  • 镜像源地址输入错误 - 检查配置文件中的URL是否正确
  • 网络问题 - 尝试切换到其他镜像源(如阿里云、中科大)
  • 包本身较大 - 有些大型包(如TensorFlow)即使使用镜像源也需要较长时间

如何查看当前pip使用的源?

执行以下命令:

config list

使用镜像源是否安全?

国内主流镜像源(清华、阿里云、中科大等)都提供官方同步服务,包内容与PyPI官方源一致,可以安全使用。

配置后出现SSL错误怎么办?

在配置文件中添加信任主机设置:

[global]
trusted-host = pypi.tuna.tsinghua.edu.cn

验证镜像源配置

配置完成后,可以通过以下方法验证:

1

查看配置信息

config list

正确配置会显示类似:

global.index-url='https://pypi.tuna.tsinghua.edu.cn/simple'
2

测试下载速度

安装一个小型包并观察下载速度:

install --no-cache-dir requests

如果显示从镜像源下载(如tuna.tsinghua.edu.cn),说明配置成功。

高级配置选项

完整pip.ini配置示例

[global]
# 主镜像源
index-url = https://pypi.tuna.tsinghua.edu.cn/simple

# 备用镜像源
extra-index-url =
    https://mirrors.aliyun.com/pypi/simple
    https://pypi.mirrors.ustc.edu.cn/simple

# 信任所有镜像源主机
trusted-host =
    pypi.tuna.tsinghua.edu.cn
    mirrors.aliyun.com
    pypi.mirrors.ustc.edu.cn

# 超时设置(秒)
timeout = 120

# 重试次数
retries = 8

# 禁用缓存
no-cache-dir = true

# 禁用二进制包(强制源码编译)
only-binary = :none: