在 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 文件夹:
- 路径:
c:\users\用户名\pip\
创建 pip.ini 文件,添加以下内容:
[global] index-url = https://pypi.tuna.tsinghua.edu.cn/simple/ trusted-host = pypi.tuna.tsinghua.edu.cn timeout = 6000
linux/macos 系统
- 创建或修改配置文件:
# 创建目录 mkdir -p ~/.pip # 创建或修改配置文件 vim ~/.pip/pip.conf
- 添加以下内容:
[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
注意事项
- 信任主机:对于非官方源,需要设置
trusted-host参数 - 超时设置:可以适当增加
timeout值避免下载超时 - ssl 验证:如果遇到 ssl 问题,可以添加
--trusted-host参数
推荐使用清华镜像源或阿里云镜像源,它们在国内的访问速度和稳定性都比较好。
到此这篇关于python设置pip镜像源的几种方法的文章就介绍到这了,更多相关python设置pip镜像源内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论