pip and 包 Management
安装, upgrade, and manage Python 包使用 pip, PyPI, and pyproject.toml.
你将学到
- 安装 and 卸载包 使用 pip
- Upgrade, downgrade, and pin 包 versions
- 搜索 and inspect 包 on PyPI
- Use pyproject.toml for modern 项目配置
- Troubleshoot 常见 pip issues
概念讲解
What Is pip?
pip 是 the Python package installer. It downloads packages from PyPI (the Python Package Index — over 400,000 packages) and installs them into your environment:
pip install requests # install latest version
pip install requests==2.31.0 # install specific version
pip install "请求>=2.30" # install minimum version
pip uninstall requests # remove a package
pip is included with Python 3.4+ — you do not need to install it separately. It is the standard way to add third-party libraries to your project.
Installing Packages
# Single package
pip install django
# Multiple packages
pip install django requests numpy
# From a requirements file
pip install -r requirements.txt
# With version constraints
pip install "django>=4.2,<5.0"
# From a Git repository
pip install git+https://github.com/user/repo.git
# In editable mode (for local development)
pip install -e .
Version specifiers:
==2.31.0— exactly this version>=2.31.0— this version or higher<3.0.0— less than this version~=2.31.0— compatible release (2.31.x)!=2.32.0— any version except this one
Upgrading and Downgrading
# Upgrade to the latest version
pip install --upgrade requests
# or
pip install -U requests
# Downgrade to a specific version
pip install requests==2.30.0
# Show what would be upgraded without doing it
pip list --outdated
Be careful with upgrades — a new version might have breaking changes. Always check the package's changelog before upgrading in production.
Inspecting Packages
# Show details about an installed package
pip show requests
# List all installed packages
pip list
# Find which packages depend on a given package
pip show requests | grep Requires
# Check a package's files
pip show -f requests
Searching PyPI
# Search PyPI (deprecated in pip 21.2+ — use the website)
pip search "HTTP 客户端"
# Instead, browse https://pypi.org
The pip 搜索 command was disabled due to abuse of the XMLRPC API. Browse [pypi.org](https://pypi.org) directly to search for packages.
pyproject.toml — Modern Project Configuration
pyproject.toml is the modern standard for Python project configuration (PEP 518/621). It replaces 设置.py and 设置.cfg:
[project]
name = "myapp"
version = "1.0.0"
description = "My awesome application"
requires-python = ">=3.10"
dependencies = [
"django>=4.2",
"请求>=2.31.0",
]
[project.optional-dependencies]
dev = ["pytest", "black", "mypy"]
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.backends._legacy:_backend"
Install in development mode:
pip install -e ".[dev]" # install with dev dependencies
Common pip Issues
pip not found — ensure Python is installed and on your PATH. On some systems, use python -m pip instead of pip to ensure you use the right Python's pip.
Permission denied — never use sudo pip install. It can break system tools. Use a virtual environment instead.
SSL certificate errors — on corporate networks, you may need to configure certificates:
pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org requests
Conflicting dependencies — when two packages require incompatible versions of a third. Use pip check to detect conflicts, and consider pip-tools or poetry for better dependency resolution.
示例代码
# --- Shell commands for pip ---
# pip install requests
# pip install "django>=4.2,<5.0"
# pip install -r requirements.txt
# pip install -e .
# pip uninstall requests
# pip install --upgrade requests
# pip list
# pip show requests
# pip check # check for dependency conflicts
# --- pyproject.toml example ---
# [project]
# name = "myapp"
# version = "1.0.0"
# requires-python = ">=3.10"
# dependencies = [
# "django>=4.2",
# "requests>=2.31.0",
# ]
# [project.optional-dependencies]
# dev = ["pytest", "black", "mypy"]
# --- Python code: inspect installed packages ---
import importlib
import subprocess
import sys
def check_package(package_name):
"""Check if a package is installed and get its version."""
try:
spec = importlib.util.find_spec(package_name)
if spec is None:
return f"{package_name}: NOT installed"
try:
version = importlib.metadata.version(package_name)
return f"{package_name}: {version} (installed)"
except importlib.metadata.PackageNotFoundError:
return f"{package_name}: installed (version unknown)"
except Exception as e:
return f"{package_name}: error - {e}"
# Check common packages
for pkg in ["json", "os", "math", "requests", "numpy", "django"]:
print(check_package(pkg))
# Show pip version
result = subprocess.run(
[sys.executable, "-m", "pip", "--version"],
capture_output=True, text=True
)
print(f"\npip info: {result.stdout.strip()}")
Shows pip commands for 安装/卸载/upgrade, pyproject.toml 示例, and Python code using importlib 到检查哪个包 是安装 and 它们的 versions.
动手试一试
- JSON Formatter
pyproject.toml and 包 metadata use structured 格式.
- CSV 到 JSON
许多 pip-安装包 (如 pandas) 工作使用 CSV and JSON 数据.
常见错误
错误写法
Using sudo pip 安装哪个能 break 系统 Python tools
正确做法
从不 use sudo 使用 pip — 它安装到 系统 Python and 能 break OS tools 那个 depend on 它. 总是 use 虚拟环境 and 安装不使用 sudo. 如果你 必须安装 globally, use 'pip 安装 --用户'.
错误写法
不 pinning versions and 获取不同 behavior 跨越 machines
正确做法
Use 'pip freeze > 需求.txt' 到记录精确 versions. Pin 使用 == for reproducible 安装. 不使用 pinning, 'pip 安装 -r 需求.txt' 可能安装不同 versions on 不同 days, causing subtle bugs.
相关资源
相关速查表
- Python Cheatsheet
pip commands, version specifiers, and pyproject.toml 语法.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。