以下是配置pip国内镜像源的完整方法及注意事项,综合主流配置方案和常见问题解决方案:


一、临时使用国内源(单次有效)

安装时通过-i参数指定镜像源:

pip3 install 包名 -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn 

推荐源地址:
清华大学:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:https://mirrors.aliyun.com/pypi/simple
中科大:https://pypi.mirrors.ustc.edu.cn/simple

二、永久配置国内源

方案1:命令行配置(推荐)
执行以下命令自动生成配置文件:

pip3 config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple 
pip3 config set install.trusted-host pypi.tuna.tsinghua.edu.cn 

配置文件路径:
Windows:C:\Users\用户名\pip\pip.ini
Linux/macOS:~/.pip/pip.conf

方案2:手动编辑配置文件
创建或修改对应系统的配置文件,添加以下内容:

[global]
index-url = https://mirrors.aliyun.com/pypi/simple 
trusted-host = mirrors.aliyun.com 

三、多镜像源配置(增强稳定性)

在配置文件中添加备用源:

[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple 
extra-index-url = 
    https://mirrors.aliyun.com/pypi/simple 
    https://pypi.doubanio.com/simple 

当主镜像源不可用时自动切换备用源

四、验证配置生效

执行命令查看当前生效配置:

pip3 config list 

正常应显示:

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

五、常见问题解决

  1. SSL证书错误
    添加--trusted-host参数或配置文件中包含trusted-host字段
  2. 配置不生效

    • 检查配置文件路径是否正确
    • 重启终端/PyCharm等IDE
    • 执行pip cache purge清除缓存
  3. 权限问题
    Windows系统需用管理员身份运行CMD,macOS/Linux前加sudo

六、主流镜像源推荐

清华大学  https://pypi.tuna.tsinghua.edu.cn/simple   同步频率高(5分钟)
阿里云  https://mirrors.aliyun.com/pypi/simple   CDN加速
豆瓣源  https://pypi.doubanio.com/simple   支持HTTP协议
腾讯云  https://mirrors.cloud.tencent.com/pypi   企业级稳定性

最后修改:2025 年 05 月 28 日
如果觉得我的文章对你有用,请随意赞赏