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


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

相关推荐
Ice__Cai21 分钟前
Flask 路由详解:构建灵活的 URL 映射系统
开发语言·python·flask
l1t43 分钟前
DeepSeek辅助编写的将xlsx格式文件中sheet1.xml按需分别保留或去掉标签的程序
xml·python·excel·wps·xlsx
l1t1 小时前
分析xml标签属性和压缩级别对xlsx文件读取解析的影响
xml·开发语言·python·sql·duckdb
Chandler_Song2 小时前
【Python代码】谷歌专利CSV处理函数
开发语言·python·pandas
测试19985 小时前
Web自动化测试:测试用例流程设计
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
山烛9 小时前
矿物分类系统开发笔记(一):数据预处理
人工智能·python·机器学习·矿物分类
集成显卡16 小时前
使用 Google 开源 AI 工具 LangExtract 进行结构化信息抽取
python·google·openai
久笙&16 小时前
对象存储解决方案:MinIO 的架构与代码实战
数据库·python·架构
不甘懦弱17 小时前
阿里云搭建flask服务器
服务器·python·flask
赵英英俊17 小时前
Python day51
人工智能·pytorch·python