外观
pip 使用国内镜像 + 代理加速安装
pip install 慢、Read timed out 超时,基本都是因为默认从境外的 PyPI 拉包。换成国内镜像源即可解决绝大多数问题。
一、临时使用镜像源(单次)
bash
pip install 包名 -i https://pypi.tuna.tsinghua.edu.cn/simple常用国内源:
| 镜像 | 地址 |
|---|---|
| 清华 TUNA | https://pypi.tuna.tsinghua.edu.cn/simple |
| 阿里云 | https://mirrors.aliyun.com/pypi/simple/ |
| 中科大 | https://pypi.mirrors.ustc.edu.cn/simple/ |
| 腾讯云 | https://mirrors.cloud.tencent.com/pypi/simple |
二、永久配置(推荐)
一次配置,以后所有 pip install 都走镜像:
bash
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip config set global.trusted-host pypi.tuna.tsinghua.edu.cn也可以直接编辑配置文件:
- Windows:
C:\Users\你的用户名\pip\pip.ini - macOS / Linux:
~/.config/pip/pip.conf或~/.pip/pip.conf
ini
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
trusted-host = pypi.tuna.tsinghua.edu.cn查看当前配置:
bash
pip config list三、给 pip 走代理
如果要从 GitHub 直接装包(pip install git+https://github.com/...),镜像救不了,得走代理:
bash
# 单次
pip install --proxy http://127.0.0.1:7890 包名
# 或用环境变量
export https_proxy=http://127.0.0.1:7890
export http_proxy=http://127.0.0.1:7890
pip install 包名Windows PowerShell:
powershell
$env:HTTPS_PROXY="http://127.0.0.1:7890"; pip install 包名四、conda 换源(顺带)
用 conda 的话,同样建议换国内源:
bash
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --set show_channel_urls yes五、常见问题
Q:报 trusted-host 相关 SSL 警告? 加上 --trusted-host pypi.tuna.tsinghua.edu.cn,或在配置文件里写 trusted-host。
Q:某个包在国内镜像上没有 / 版本旧? 镜像有同步延迟。临时用官方源装这一个:pip install 包名 -i https://pypi.org/simple。
Q:pip install git+https://github.com/... 卡住? 这是从 GitHub 拉源码,和 PyPI 镜像无关,走代理(方法三)或参考 git clone 加速。
小结
- 普通装包:永久配清华/阿里源(方法二),一劳永逸。
- 从 GitHub 装包:走 代理。
- 镜像缺包时临时切回官方源。
本文仅供技术学习与研究,请遵守所在国家/地区法律法规。