Python3 pip
Installing, freezing, pinning, offline installs and the dependency-hell escape hatches.
Key PointsPin exact versions in production, use `python -m pip` to be sure which interpreter you are installing into.
Basic Commands
Bash
python -m pip install requests
python -m pip install "fastapi>=0.110,<1.0"
python -m pip install --upgrade pip
python -m pip uninstall requests
python -m pip list
python -m pip show requestspip alone may point at a different interpreter than python. Always write python -m pip inside a venv.Reproducible Installs
Bash
# 导出当前环境的精确版本
python -m pip freeze > requirements.txt
# 还原
python -m pip install -r requirements.txt
# 只装依赖树里的顶层包(不含传递依赖)
pip install pip-tools
pip-compile requirements.in -o requirements.txtMirrors and Offline
Bash
# 国内镜像
python -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests
# 永久配置
python -m pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
# 离线:先下载 wheel,再到目标机器安装
python -m pip download -d ./wheels -r requirements.txt
python -m pip install --no-index --find-links=./wheels -r requirements.txtWhen Installs Fail
| Symptom | Cause | Fix |
|---|---|---|
| Building wheel failed | No prebuilt wheel for your platform | Install build tools, or pin an older version |
| Permission denied | Installing into system Python | Use a venv |
| VersionConflict | Two packages need different versions | pip-compile / uv lock |
| SSL error | Corporate proxy or old certifi | Set --proxy / upgrade certifi |
pip install never downgrades an existing package unless you ask. If an import suddenly breaks, check pip list for a half-upgraded tree.基本命令
Bash
python -m pip install requests
python -m pip install "fastapi>=0.110,<1.0"
python -m pip install --upgrade pip
python -m pip uninstall requests
python -m pip list
python -m pip show requests直接写
pip 可能指向另一个解释器。在 venv 里一律用 python -m pip。可复现安装
Bash
# 导出当前环境的精确版本
python -m pip freeze > requirements.txt
# 还原
python -m pip install -r requirements.txt
# 只装依赖树里的顶层包(不含传递依赖)
pip install pip-tools
pip-compile requirements.in -o requirements.txt镜像与离线
Bash
# 国内镜像
python -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests
# 永久配置
python -m pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
# 离线:先下载 wheel,再到目标机器安装
python -m pip download -d ./wheels -r requirements.txt
python -m pip install --no-index --find-links=./wheels -r requirements.txt安装失败时
| 现象 | 原因 | 处理 |
|---|---|---|
| 构建 wheel 失败 | 该平台没有预编译 wheel | 装编译工具,或锁定旧版本 |
| 权限不足 | 装进了系统 Python | 用虚拟环境 |
| 版本冲突 | 两个包要求不同版本 | 用 pip-compile / uv lock |
| SSL 错误 | 公司代理或旧证书 | 设 --proxy / 升级 certifi |
pip install 默认不会降级已安装的包。如果某个 import 突然失败,先 pip list 看看依赖树是不是被升坏了一半。