如何更改 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 包的下载速度,从而提升开发效率。希望本文对大家有所帮助!


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

相关推荐
前端付豪15 分钟前
13、你还在 print 调试🧾?教你写出自己的日志系统
后端·python
这里有鱼汤20 分钟前
hvPlot:用你熟悉的 Pandas,画出你没见过的炫图
后端·python
源码站~31 分钟前
基于Flask+Vue的豆瓣音乐分析与推荐系统
vue.js·python·flask·毕业设计·毕设·校园·豆瓣音乐
MessiGo37 分钟前
Python 爬虫实战 | 国家医保
python
chanalbert1 小时前
Spring 6 源码深度掘金:66+核心原理与高频面试攻坚指南
python·spring·面试
都叫我大帅哥2 小时前
向量数据库Milvus:非结构化数据的救星,AI开发者的瑞士军刀
java·python
冰糖猕猴桃3 小时前
【Python】进阶 - 数据结构与算法
开发语言·数据结构·python·算法·时间复杂度、空间复杂度·树、二叉树·堆、图
天水幼麟3 小时前
python学习笔记(深度学习)
笔记·python·学习
巴里巴气3 小时前
安装GPU版本的Pytorch
人工智能·pytorch·python
wt_cs3 小时前
银行回单ocr api集成解析-图像文字识别-文字识别技术
开发语言·python