极简工具箱

免费在线工具 · 本地计算 · 无需上传

pip 装不上包怎么办:镜像源、依赖冲突与版本锁定

`pip install` 卡在下载、装完 import 报错、两个包要求不同版本的同一个依赖——这三类问题占了 pip 使用问题的九成。

广告位(百度联盟)

一、换国内镜像源

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   # 看某个包被谁依赖

常见原因:两个包要求同一个依赖的不同大版本。解决方式:

  1. 升级其中一个包到兼容版本。
  2. 用虚拟环境隔离(见 虚拟环境)。
  3. 实在无法兼容,用 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 check / pipdeptree 定位;编译失败找 whl 或装 Build Tools;离线用 pip download + --no-index;命令行工具用 pipx;应用项目提交锁文件。

本文相关工具(本地计算,无需上传)

更多使用教程