python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python设置pip镜像源

Python设置pip镜像源的几种方法

作者:冉成未来

本文介绍了在Python中使用pip设置镜像源的方法,包括临时使用、永久配置、使用命令配置、查看配置、恢复默认源和使用多个镜像源等,推荐使用清华镜像源或阿里云镜像源,并提供了注意事项,如信任主机、超时设置和SSL验证,需要的朋友可以参考下

在 Python 中使用 pip 设置镜像源可以显著提升包下载速度,特别是在国内网络环境下。以下是几种设置方法:

1. 临时使用镜像源

在 pip 安装命令中直接指定镜像源:

# 使用清华镜像源
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ package-name

# 使用阿里云镜像源
pip install -i https://mirrors.aliyun.com/pypi/simple/ package-name

# 使用豆瓣镜像源
pip install -i https://pypi.douban.com/simple/ package-name

# 使用中科大镜像源
pip install -i https://pypi.mirrors.ustc.edu.cn/simple/ package-name

2. 永久配置镜像源

Windows 系统

在用户目录下创建 pip 文件夹

创建 pip.ini 文件,添加以下内容:

[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple/
trusted-host = pypi.tuna.tsinghua.edu.cn
timeout = 6000

Linux/macOS 系统

  1. 创建或修改配置文件
# 创建目录
mkdir -p ~/.pip

# 创建或修改配置文件
vim ~/.pip/pip.conf
  1. 添加以下内容
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple/
trusted-host = pypi.tuna.tsinghua.edu.cn
timeout = 6000

3. 使用命令配置

# 设置清华源
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple/
pip config set global.trusted-host pypi.tuna.tsinghua.edu.cn

# 设置阿里云源
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
pip config set global.trusted-host mirrors.aliyun.com

4. 查看当前配置

# 查看所有配置
pip config list

# 查看指定配置项
pip config get global.index-url

5. 常用国内镜像源

# 清华镜像源
https://pypi.tuna.tsinghua.edu.cn/simple/

# 阿里云镜像源
https://mirrors.aliyun.com/pypi/simple/

# 豆瓣镜像源
https://pypi.douban.com/simple/

# 中科大镜像源
https://pypi.mirrors.ustc.edu.cn/simple/

# 华为云镜像源
https://repo.huaweicloud.com/repository/pypi/simple/

6. 恢复默认源

如果需要恢复官方源:

# 删除配置文件
# Windows: 删除 C:\Users\用户名\pip\pip.ini
# Linux/macOS: 删除 ~/.pip/pip.conf

# 或者使用命令重置
pip config unset global.index-url

7. 使用多个镜像源

如果需要配置多个镜像源作为备份:

[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple/
extra-index-url = 
    https://mirrors.aliyun.com/pypi/simple/
    https://pypi.douban.com/simple/
trusted-host =
    pypi.tuna.tsinghua.edu.cn
    mirrors.aliyun.com
    pypi.douban.com

注意事项

  1. 信任主机:对于非官方源,需要设置 trusted-host 参数
  2. 超时设置:可以适当增加 timeout 值避免下载超时
  3. SSL 验证:如果遇到 SSL 问题,可以添加 --trusted-host 参数

推荐使用清华镜像源或阿里云镜像源,它们在国内的访问速度和稳定性都比较好。

到此这篇关于Python设置pip镜像源的几种方法的文章就介绍到这了,更多相关Python设置pip镜像源内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文