Python 虚拟环境的创建

Isolating dependencies per project, installing from requirements.txt, and pinning versions.

Beginner
Key PointsEvery project gets its own venv; commit a lock file, not your site-packages.

Why Isolate

A single global site-packages means project A upgrading a library can break project B. A venv is a private directory of packages plus a private interpreter shim.

Create and Activate

Bash
# 创建(Python 3.3+ 内置,不需要 virtualenv)
python3 -m venv .venv

# 激活
source .venv/bin/activate        # macOS / Linux
.venv\Scripts\activate           # Windows (cmd / PowerShell)

# 退出
deactivate

pip Workflow

Bash
python -m pip install --upgrade pip
python -m pip install fastapi uvicorn[standard]

# 导出精确版本(可复现)
python -m pip freeze > requirements.txt

# 在另一台机器还原
python -m pip install -r requirements.txt

# 只看装了什么
python -m pip list
CommandPurpose
pip install pkg==1.2.3Pin an exact version
pip install -r req.txtInstall a dependency set
pip install -e .Editable install of a local project
pip uninstall pkgRemove a package
pip download pkg -d ./wheelsVendor wheels for offline install

requirements.txt vs pyproject.toml

requirements.txt is the simple, universal format. pyproject.toml is the modern project metadata standard (PEP 621) used by poetry/uv/hatch — pick one and be consistent.

TOML
[project]
name = "myapp"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = ["fastapi>=0.110", "uvicorn[standard]>=0.27"]

Faster Tooling

Bash
# uv:Rust 实现,创建环境与安装都更快
uv venv
uv pip install fastapi uvicorn

# 或一条命令跑脚本,自动管理环境
uv run main.py
Never commit .venv/ or __pycache__/. Add both to .gitignore — a committed venv is thousands of machine-specific files.

Friends & Partners