pip 是 Python 的标准包安装器,用于从 PyPI 安装和管理依赖,并遵循现代打包标准与隔离环境约束。
用途:安装、更新和隔离 Python 依赖;通过 pip-tools 与约束文件(-c constraints.txt)实现确定性版本锁定;安装基于 pyproject.toml 的现代项目(PEP 517/621);使用 SHA256 哈希(--require-hashes)进行安全与完整性校验。
主要能力:支持虚拟环境、requirements.txt、wheels、constraints、pip-tools、可编辑安装(pip install -e .[dev,test])、漏洞审计(pip-audit --desc)、无缓存安装(--no-cache-dir)以及严格哈希校验安装。
用法示例:先创建并激活虚拟环境:python -m venv .venv 与 source .venv/bin/activate,随后 pip install requests 并 pip freeze > requirements.txt。锁定依赖可用 pip-compile --generate-hashes requirements.in -o requirements.txt 和 pip-sync requirements.txt。哈希校验安装:pip install --no-deps --require-hashes -r constraints.txt。
适用场景:本地开发、CI 依赖检查、Docker 镜像构建、生产部署的依赖锁定与供应链安全验证。
限制与注意:不要在系统 Python 下执行 sudo pip install;生产环境应使用 pip-compile 生成锁定文件并启用 --require-hashes。常见错误包括 externally-managed-environment(PEP 668,应改用虚拟环境)、找不到满足要求的版本(包名拼写或 Python 版本不兼容)、构建 wheel 失败(缺少编译器或开发头文件)。更多细节参见 pip 官方文档。