Python 虚拟环境的创建
Isolating dependencies per project, installing from requirements.txt, and pinning versions.
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)
# 退出
deactivatepip 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| Command | Purpose |
|---|---|
| pip install pkg==1.2.3 | Pin an exact version |
| pip install -r req.txt | Install a dependency set |
| pip install -e . | Editable install of a local project |
| pip uninstall pkg | Remove a package |
| pip download pkg -d ./wheels | Vendor 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.pyNever commit
.venv/ or __pycache__/. Add both to .gitignore — a committed venv is thousands of machine-specific files.为什么隔离
全局共用一个 site-packages,意味着 A 项目升级库可能搞坏 B 项目。venv 就是一个私有包目录加上一个私有解释器入口。
创建与激活
Bash
# 创建(Python 3.3+ 内置,不需要 virtualenv)
python3 -m venv .venv
# 激活
source .venv/bin/activate # macOS / Linux
.venv\Scripts\activate # Windows (cmd / PowerShell)
# 退出
deactivatepip 工作流
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| 命令 | 用途 |
|---|---|
| pip install pkg==1.2.3 | 锁定精确版本 |
| pip install -r req.txt | 按清单安装 |
| pip install -e . | 本地项目可编辑安装 |
| pip uninstall pkg | 卸载包 |
| pip download pkg -d ./wheels | 离线安装用的 wheel |
requirements.txt 与 pyproject.toml
requirements.txt 简单通用;pyproject.toml 是现代项目元数据标准(PEP 621),poetry/uv/hatch 都用它 —— 选一个并保持一致。
TOML
[project]
name = "myapp"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = ["fastapi>=0.110", "uvicorn[standard]>=0.27"]更快的工具链
Bash
# uv:Rust 实现,创建环境与安装都更快
uv venv
uv pip install fastapi uvicorn
# 或一条命令跑脚本,自动管理环境
uv run main.py不要提交
.venv/ 和 __pycache__/,把它们写进 .gitignore —— 提交 venv 等于提交上千个与机器绑定的文件。