如何更改 Python pip 源为国内源

在使用 Python 安装包工具 pip 时,经常会遇到下载速度慢的问题。这通常是因为默认使用的官方源 https://pypi.org/simple 在国内访问速度较慢。为了提高下载速度,我们可以将 pip 源更改为国内的镜像源。本文将介绍如何临时和永久地更改 pip 源为国内源。

临时换源

临时换源方法是在 pip 安装包时加上 -i 参数,并指定镜像源的 URL。

清华源

python 复制代码
pip install package_name -i https://pypi.tuna.tsinghua.edu.cn/simple

阿里源

python 复制代码
pip install package_name -i https://mirrors.aliyun.com/pypi/simple/

腾讯源

python 复制代码
pip install package_name -i http://mirrors.cloud.tencent.com/pypi/simple

豆瓣源

python 复制代码
pip install package_name -i http://pypi.douban.com/simple/

永久换源

永久换源方法是修改 pip 的配置文件,使所有包的下载都从指定的镜像源进行。

修改配置文件

Linux 和 macOS

在根目录下创建或修改 ~/.pip/pip.conf 文件,添加以下内容:

python 复制代码
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple

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

其他源的配置:

  • 阿里源:
python 复制代码
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/

[install]
trusted-host = mirrors.aliyun.com
  • 腾讯源:
python 复制代码
[global]
index-url = http://mirrors.cloud.tencent.com/pypi/simple

[install]
trusted-host = mirrors.cloud.tencent.com
  • 豆瓣源:
python 复制代码
[global]
index-url = http://pypi.douban.com/simple/

[install]
trusted-host = pypi.douban.com
Windows

%HOMEPATH%\pip\pip.ini 中添加或修改以下内容:

python 复制代码
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple

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

其他源的配置与 Linux 类似,只需将 pip.conf 文件路径替换为 pip.ini

恢复默认源

如果需要恢复 pip 的默认源,可以使用以下命令:

python 复制代码
pip config unset global.index-url

常见问题

安装包时出现"不受信任的主机"警告

在安装包时,如果出现类似以下的警告信息:

python 复制代码
The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS it is recommended to use HTTPS instead, otherwise you may silence this warning and allow it anyways with '--trusted-host mirrors.aliyun.com'.

这是因为 pip 认为该源不受信任。可以使用 --trusted-host 参数临时解决:

python 复制代码
pip install package_name --trusted-host mirrors.aliyun.com

永久信任指定源

在配置文件中添加信任源的设置,以一劳永逸:

python 复制代码
[install]
trusted-host = mirrors.aliyun.com

结语

通过以上方法,我们可以有效地提高 pip 包的下载速度,从而提升开发效率。希望本文对大家有所帮助!


如果您有任何问题或建议,欢迎在评论区留言讨论。

相关推荐
fish_study_csdn5 小时前
pytest 技术总结
开发语言·python·pytest
咖啡调调。5 小时前
使用Django框架表单
后端·python·django
BO_S__5 小时前
python调用ffmpeg对截取视频片段,可批量处理
python·ffmpeg·音视频
就叫飞六吧5 小时前
如何判断你的PyTorch是GPU版还是CPU版?
人工智能·pytorch·python
pyengine7 小时前
基于pandoc的MarkDown格式与word相互转换小工具开发(pyqt5)
开发语言·python·qt·word
YuSun_WK7 小时前
配置MambaIRv2: Attentive State Space Restoration的环境
开发语言·python
Nick_zcy7 小时前
开发基于python的商品推荐系统,前端框架和后端框架的选择比较
开发语言·python·前端框架·flask·fastapi
一点.点8 小时前
李沐动手深度学习(pycharm中运行笔记)——04.数据操作
pytorch·笔记·python·深度学习·pycharm·动手深度学习
Niuguangshuo8 小时前
Python 设计模式:访问者模式
python·设计模式·访问者模式
Jamesvalley8 小时前
【Django】新增字段后兼容旧接口 This field is required
后端·python·django