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


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

相关推荐
databook1 天前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室1 天前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三1 天前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i2 天前
django中的FBV 和 CBV
python·django
c8i2 天前
python中的闭包和装饰器
python
这里有鱼汤2 天前
小白必看:QMT里的miniQMT入门教程
后端·python