一、换国内镜像源
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 install requests -i https://mirrors.aliyun.com/pypi/simple/
常用源:清华 TUNA、阿里云、中科大、腾讯云。配置会写入 ~/.config/pip/pip.conf(Linux/macOS)或 %APPDATA%\pip\pip.ini(Windows),一次配置长期生效。
如果公司有内网源,优先用内网的,公网源可能被墙或限速。
二、常用参数
pip install requests # 安装
pip install requests==2.31.0 # 指定版本
pip install "requests>=2.28,<3" # 版本范围
pip install -U requests # 升级
pip install -r requirements.txt # 按清单安装
pip install -e . # 以可编辑模式安装本地项目
pip uninstall requests
pip list --outdated # 可升级的包
pip show requests # 包信息与依赖
pip install -e . 用于开发自己的包:源码改动立即生效,不用反复安装。
三、依赖冲突
典型报错:
ERROR: Cannot install packageA==1.0 and packageB==2.0 because these package versions have conflicting dependencies.
排查步骤:
pip check # 检查已安装包的依赖是否满足
pipdeptree # 打印依赖树(需先 pip install pipdeptree)
pipdeptree -p requests # 看某个包被谁依赖
常见原因:两个包要求同一个依赖的不同大版本。解决方式:
- 升级其中一个包到兼容版本。
- 用虚拟环境隔离(见 虚拟环境)。
- 实在无法兼容,用
pip install --no-deps跳过依赖检查(有风险,需自行保证兼容)。
四、装不上的几类原因
| 报错 | 原因 |
|---|---|
Could not find a version that satisfies the requirement | 包名错、Python 版本不支持、源里没有该平台包 |
Failed building wheel for xxx | 缺编译工具(gcc、python3-dev)或系统库 |
SSL: CERTIFICATE_VERIFY_FAILED | 证书问题,公司代理拦截 |
卡在 Collecting | 网络慢,换源 |
Permission denied | 装到系统目录,需虚拟环境或 --user |
需要编译的包(如 mysqlclient、lxml)在 Windows 上常常没有预编译 whl,建议优先找纯 Python 替代(pymysql、httpx),或安装对应的 Build Tools。
五、离线安装
内网服务器无法联网时:
# 有网机器上打包
pip download -r requirements.txt -d ./pkgs --platform manylinux2014_x86_64 --only-binary=:all:
# 拷到目标机器
pip install --no-index --find-links=./pkgs -r requirements.txt
注意 --platform 和 Python 版本必须与目标环境一致,否则下载的 whl 装不上。
六、命令行工具用 pipx
像 black、poetry、httpie 这类「提供命令」的包,装进项目虚拟环境不方便全局调用,装全局又会污染。用 pipx:
pipx install black
pipx list
它给每个工具建独立环境,只把可执行文件链接到 PATH,互不干扰。
七、版本锁定
requirements.txt 里写死版本(==)能保证复现,但升级麻烦;写范围(>=)灵活但可能装到不兼容的新版。
比较稳的做法:
- 应用项目:用锁文件(
pip-tools生成requirements.txt,或poetry.lock、uv.lock),提交到仓库。 - 库项目:
pyproject.toml里写范围,不锁死,让使用者自己决定。
八、几个习惯
- 装包前先确认在虚拟环境里(
which pip)。 - 别用
sudo pip install,会把系统包搞乱。 - 定期
pip list --outdated看安全更新,但生产环境升级要测。 - 遇到奇怪问题先
pip install --force-reinstall试一次,再排查环境。
小结
先配国内源;冲突用 pip check / pipdeptree 定位;编译失败找 whl 或装 Build Tools;离线用 pip download + --no-index;命令行工具用 pipx;应用项目提交锁文件。