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


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

相关推荐
诗句藏于尽头5 小时前
Django模型与数据库表映射的两种方式
数据库·python·django
智数研析社5 小时前
9120 部 TMDb 高分电影数据集 | 7 列全维度指标 (评分 / 热度 / 剧情)+API 权威源 | 电影趋势分析 / 推荐系统 / NLP 建模用
大数据·人工智能·python·深度学习·数据分析·数据集·数据清洗
扯淡的闲人5 小时前
多语言编码Agent解决方案(5)-IntelliJ插件实现
开发语言·python
moxiaoran57535 小时前
Flask学习笔记(一)
后端·python·flask
秋氘渔6 小时前
迭代器和生成器的区别与联系
python·迭代器·生成器·可迭代对象
Gu_shiwww6 小时前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
Dxy12393102167 小时前
python把文件从一个文件复制到另一个文件夹
开发语言·python
sonrisa_8 小时前
collections模块
python
折翼的恶魔8 小时前
数据分析:排序
python·数据分析·pandas
天雪浪子8 小时前
Python入门教程之赋值运算符
开发语言·python