【5分钟教程】用 `uv` 构建现代 Python 项目:从目录结构到打包测试一条龙
🎯 本文将带你一步步构建一个兼容 PEP 标准、快如闪电、结构清晰、测试完善的 Python 工程体系,替代 pip、setuptools、conda、setup.py 等传统方式。整合 uv + pyproject.toml + ruff + pytest + coverage 一体化开发体验。
📁 项目结构总览
我们采用社区推荐的 src/ 布局,结合 pyproject.toml 配置,形成如下目录:
awesome-project/
├── pyproject.toml # ✅ 全局配置,替代 setup.py
├── requirements.txt # ✅ 可选,兼容 pip
├── uv.lock # ✅ uv 快照(可选)
├── .venv/ # ✅ 本地虚拟环境(uv venv 创建)
├── src/
│ └── awesome/ # ✅ 你的项目代码(支持多包)
│ └── __init__.py
├── tests/ # ✅ 测试目录(pytest 自动发现)
│ └── test_example.py
├── ruff.toml # ✅ 代码风格配置
└── README.md # ✅ 项目说明(包含安装、使用、发布)
🛠️ 步骤 1:使用 uv 创建虚拟环境与安装依赖
# 初始化项目目录
mkdir awesome-project && cd awesome-project
# 创建本地虚拟环境
uv venv .venv
source .venv/bin/activate
# 安装核心依赖
uv pip install requests fastapi
# 安装开发依赖
uv pip install pytest coverage ruff
# 快照依赖(可选)
uv snapshot
⚙️ 步骤 2:配置 pyproject.toml(替代 setup.py)
[project]
name = "awesome"
version = "0.1.0"
description = "A blazing-fast uv-powered Python project"
readme = "README.md"
authors = [{name = "Feilong", email = "feilong@example.com"}]
requires-python = ">=3.9"
dependencies = ["requests", "fastapi"]
[project.optional-dependencies]
dev = ["pytest", "coverage", "ruff"]
[build-system]
requires = ["uv"]
build-backend = "uv.build"
🎯 步骤 3:代码质量工具(ruff)配置
创建 ruff.toml:
[tool.ruff]
src = ["src"]
line-length = 100
target-version = "py39"
格式化与检查:
ruff check src tests
ruff format src tests
🧪 步骤 4:测试与覆盖率(pytest + coverage)
新增配置(可合并进 pyproject.toml):
[tool.pytest.ini_options]
addopts = "--tb=short -q"
testpaths = ["tests"]
[tool.coverage.run]
branch = true
source = ["src/awesome"]
[tool.coverage.report]
show_missing = true
运行:
pytest
coverage run -m pytest
coverage report -m
📦 步骤 5:构建与发布(uv build + twine)
构建产物
uv build
构建完成后生成:
dist/
├── awesome-0.1.0-py3-none-any.whl
├── awesome-0.1.0.tar.gz
发布 PyPI(使用 twine)
pip install twine
twine upload dist/*
可选 .pypirc:
[distutils]
index-servers = pypi
[pypi]
username = __token__
password = pypi-<your-token>
✅ 可选:开发者模式安装
用于边写边测试:
uv pip install -e .
🚦 Github Actions 自动化(CI)
# .github/workflows/test.yml
name: Test & Build
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.9'
- name: Install uv
run: pip install uv
- name: Install deps
run: uv pip install .[dev]
- name: Lint
run: ruff check src tests
- name: Test
run: coverage run -m pytest
- name: Coverage Report
run: coverage report -m
- name: Build
run: uv build
🧠 总结
| 能力 | 传统工具 | uv 工具链替代 |
|---|---|---|
| 虚拟环境 | venv / conda |
uv venv |
| 安装依赖 | pip / poetry |
uv pip install |
| 构建发布包 | setup.py + wheel |
pyproject.toml + uv build |
| 开发模式安装 | pip install -e . |
uv pip install -e . |
| 代码风格 | flake8 + isort + black |
ruff |
| 测试覆盖 | pytest + coverage |
同上,自动集成 |
| 发布 PyPI | twine upload |
uv build + twine upload |
--end--

浙公网安备 33010602011771号