pip 安装超时失败?镜像源、代理与缓存的实用解决手册
Python 新手最常卡在 pip install 的红色超时:Read timed out、ConnectionError。这通常是网络到官方源 PyPI 不稳定所致,而非代码问题。下面从源、参数到环境逐层解决。
一、换成离你更近的镜像源
把默认 PyPI 换成国内镜像是最立竿见影的办法。临时使用:
pip install 包名 -i https://pypi.tuna.tsinghua.edu.cn/simple- 阿里云:
https://mirrors.aliyun.com/pypi/simple;中科大:https://pypi.mirrors.ustc.edu.cn/simple - 永久生效:新建
%APPDATA%\pip\pip.conf(Windows)或~/.pip/pip.conf(Linux/macOS),写入[global] index-url = https://pypi.tuna.tsinghua.edu.cn/simple。
二、调大超时与重试
网络慢时默认 15 秒太短。加参数放宽:
pip install 包名 --default-timeout=120避免中途断开。- 加
--retries 10与--timeout 120提升健壮性。
三、公司网络下的代理设置
若处在需要代理的内网,pip 不会自动读系统代理。显式指定:
pip install 包名 --proxy http://user:pass@host:port- 或设置环境变量
set HTTP_PROXY=...与set HTTPS_PROXY=...后再安装。
四、离线环境与缓存复用
- 有网机器先
pip download 包名 -d ./wheels下载离线包,再到无网机器pip install --no-index --find-links ./wheels 包名。 - 本机已有缓存时加
--cache-dir指定,或用pip install --upgrade复用已下载的 wheel 避免重复拉取。
五、版本与解析失败
报错 Could not find a version 多因 Python 版本过低或包名拼错。用 python --version 核对,必要时创建虚拟环境:python -m venv venv 后激活再装,隔离系统依赖冲突。
技术小结:pip 网络失败的本质是『源远、超时短、代理缺』。换镜像、加超时、配代理三步覆盖绝大多数场景;离线环境用 download/find-links 转移安装,workon 虚拟环境则能规避版本错配。