uv + pyproject.toml 实现多环境管理:optional-dependencies 定义环境依赖,--venv-path 隔离环境,锁文件保证一致性。
核心优势
| 特性 | 说明 |
|---|
| 速度 | 安装比 pip 快 10-100 倍 |
| 标准化 | pyproject.toml 统一管理 |
| 多环境 | optional-dependencies 定义不同依赖组 |
| 一致性 | 锁文件保证团队环境相同 |
安装 uv
1
2
3
4
5
| # macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# 验证
uv --version
|
pyproject.toml 配置
1
2
3
4
5
6
7
8
9
10
11
12
13
| [project]
name = "my_project"
version = "0.1.0"
requires-python = ">=3.10,<3.12"
dependencies = [
"duckdb>=0.10.0",
"pandas>=2.0.0"
]
[project.optional-dependencies]
dev = ["pytest>=7.0.0", "black>=24.0.0", "ipython>=8.0.0"]
test = ["pytest>=7.0.0", "pytest-cov>=4.0.0"]
prod-ext = ["prometheus-client>=0.20.0"]
|
创建多环境
1
2
3
4
5
6
7
8
9
10
11
| # 生产环境(核心依赖)
uv venv --python 3.11 --venv-path .venv-prod
uv pip install . --venv-path .venv-prod
# 开发环境(核心 + dev)
uv venv --python 3.11 --venv-path .venv-dev
uv pip install .[dev] --venv-path .venv-dev
# 测试环境(核心 + test)
uv venv --python 3.10 --venv-path .venv-test
uv pip install .[test] --venv-path .venv-test
|
环境切换
| 系统 | 激活命令 |
|---|
| macOS/Linux | source .venv-dev/bin/activate |
| Windows | .venv-dev\Scripts\Activate.ps1 |
退出:deactivate
依赖管理
1
2
3
4
5
6
7
8
9
10
11
12
13
| # 添加依赖
uv add requests --venv-path .venv-prod # 核心依赖
uv add "rich>=13.0.0" --dev --venv-path .venv-dev # dev 组
# 更新依赖
uv pip install --upgrade .[dev] --venv-path .venv-dev
# 锁文件
uv lock --python 3.11 -o uv-prod.lock
uv pip install --locked -r uv-prod.lock --venv-path .venv-prod
# 导出 requirements
uv pip freeze --venv-path .venv-prod > requirements-prod.txt
|
切换脚本
1
2
3
4
5
6
7
8
| #!/bin/bash
# env.sh
case "$1" in
dev) source .venv-dev/bin/activate ;;
test) source .venv-test/bin/activate ;;
prod) source .venv-prod/bin/activate ;;
*) echo "用法: ./env.sh [dev|test|prod]" ;;
esac
|
CI/CD 集成
1
2
3
4
5
6
| steps:
- uses: actions/checkout@v4
- run: curl -LsSf https://astral.sh/uv/install.sh | sh
- run: uv venv --python 3.11 --venv-path .venv-prod
- run: uv pip install --locked -r uv-prod.lock --venv-path .venv-prod
- run: . .venv-prod/bin/activate && pytest
|
Comments