pip 安装加速方案指南
问题背景
pip 是 Python 的包管理工具,但在国内使用时经常会遇到下载速度慢、超时、无法连接等问题,这通常是因为默认的 PyPI 官方源服务器在国外。本文档介绍多种解决 pip 安装慢的方法。
方案一:使用国内镜像源
临时使用
在安装包时临时指定镜像源:
# 使用阿里云镜像源安装包
pip install 包名 -i https://mirrors.aliyun.com/pypi/simple/
# 示例:安装 numpy
pip install numpy -i https://mirrors.aliyun.com/pypi/simple/
永久配置
- Linux/MacOS 创建或修改
~/.pip/pip.conf
文件:
mkdir -p ~/.pip
cat > ~/.pip/pip.conf << EOF
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
trusted-host = mirrors.aliyun.com
EOF
- Windows 创建或修改
%APPDATA%\pip\pip.ini
文件:
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
trusted-host = mirrors.aliyun.com
国内常用镜像源
源名称 | 地址 | 备注 |
---|---|---|
阿里云 | https://mirrors.aliyun.com/pypi/simple/ | 推荐,稳定 |
清华大学 | https://pypi.tuna.tsinghua.edu.cn/simple/ | 教育网速度快 |
中国科技大学 | https://pypi.mirrors.ustc.edu.cn/simple/ | 教育网速度快 |
豆瓣 | https://pypi.douban.com/simple/ | 较稳定 |
华为云 | https://repo.huaweicloud.com/repository/pypi/simple/ | 企业级 |
方案二:使用 pip 缓存
pip 会缓存下载的包,配置缓存可提高重复安装的速度:
# 查看缓存位置
pip config list
# 启用缓存(默认已启用)
pip config set global.cache-dir ~/.pip/cache
方案三:使用镜像站的 wheel 预编译包
wheel 是预编译的包格式,安装时无需从源码编译,速度更快:
# 优先安装wheel包
pip install --prefer-binary 包名
方案四:批量离线安装
批量下载依赖包
# 将依赖下载到指定目录
pip download -d ./packages 包名
# 下载包及其所有依赖
pip download -d ./packages -r requirements.txt
离线安装
# 从本地目录安装
pip install --no-index --find-links=./packages 包名
# 安装本地 .whl 文件
pip install ./packages/example-1.0.0-py3-none-any.whl
方案五:使用代理服务器
配置系统代理
# Linux/MacOS 设置代理
export http_proxy=http://代理服务器:端口
export https_proxy=http://代理服务器:端口
# Windows 设置代理
set http_proxy=http://代理服务器:端口
set https_proxy=http://代理服务器:端口
配置 pip 代理
在 pip.conf
或 pip.ini
中添加:
[global]
proxy = http://代理服务器:端口
方案六:优化安装参数
# 并行安装依赖
pip install 包名 --use-feature=2020-resolver
# 跳过已安装的包
pip install --no-deps --ignore-installed 包名
方案七:使用 conda 代替 pip
在某些情况下,conda 可能比 pip 有更好的网络性能:
# 添加国内镜像
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --set show_channel_urls yes
# 安装包
conda install 包名
方案八:通过私有 PyPI 服务器
对于企业环境,可以搭建私有 PyPI 服务器:
# 安装 pypiserver
pip install pypiserver
# 运行服务器
pypiserver -p 8080 ~/packages
# 配置客户端使用私有服务器
pip install 包名 -i http://私有服务器地址:8080/simple
故障排除
-
提示 “SSLError”:添加信任参数
pip install 包名 -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
-
提示 “Failed to establish a new connection”:检查网络连接或尝试其他镜像源
-
提示 “timeout”:增加超时时间
pip install 包名 --timeout 100
最佳实践
- 推荐优先使用方案一(国内镜像源)
- 企业环境推荐搭建私有 PyPI 服务器
- 在多台机器上工作时,考虑使用离线包集合
- 系统软件包中的Python包尽量通过系统包管理器安装