Python 项目标准工作流(2024+ 推荐)

# Python 项目标准工作流(2024+ 推荐)

原则

  • 永远用 python -m xxx
  • 永远在虚拟环境中开发
  • pyproject.toml 作为唯一配置入口

# 一、从零创建项目

# 1. 创建项目目录
mkdir myapp && cd myapp

# 2. 确认 python / pip 来源 ✅
# macOS / Linux
which python
# Windows (PowerShell)
where python
python -m pip --version

# 3. 用“当前 python”创建虚拟环境
python -m venv .venv

# 4. 激活虚拟环境
# macOS / Linux
source .venv/bin/activate
# Windows (PowerShell)
.venv\Scripts\Activate.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 二、初始化 pyproject.toml

创建 pyproject.toml(最小可用版):

[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "myapp"
version = "0.1.0"
requires-python = ">=3.9"
dependencies = [
    "requests>=2.25.0",
]

[project.optional-dependencies]
dev = [
    "pytest",
    "ruff",
    "black",
    "mypy",
]

[tool.ruff]
line-length = 88

[tool.pytest.ini_options]
testpaths = ["tests"]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

常见工具组合:

ruff        → 代码规范 & 风格,检查代码好不好、规不规范
pytest      → 测试,验证代码对不对
pytest-cov  → 测试覆盖率
mypy        → 类型检查(可选)
black       → 统一代码长什么样(📌 ruff 现在也支持格式化(ruff format),目标是替代 black)
pre-commit  → 提交前自动跑 ruff + pytest
1
2
3
4
5
6

# 三、安装依赖(核心规则)

# ✅ 安装项目本身 + 运行依赖
python -m pip install -e .

# ✅ 安装开发依赖
python -m pip install -e ".[dev]"
1
2
3
4
5

📌 记忆口诀

python -m pip install -e . =

“用这个 python,装这个项目的依赖,并让我改代码立刻生效”

# 四、日常开发命令

在现代 Python 项目中,典型流程是:

写代码
 ↓
ruff 检查 / 格式化(保证代码规范)
 ↓
pytest 跑测试(保证代码正确)
 ↓
提交 / CI 通过
1
2
3
4
5
6
7

日常开发命令:

# 代码检查
python -m ruff check .
python -m black .
python -m mypy .

# 运行测试
python -m pytest

# 运行项目
python -m myapp
1
2
3
4
5
6
7
8
9
10

全部用 python -m,避免工具与解释器不一致

# 五、锁定依赖(生产部署推荐)

# 方式一:pip(传统但稳)

# 从 pyproject.toml 生成锁文件
python -m pip freeze > requirements.txt

# 生产环境安装
python -m pip install -r requirements.txt
1
2
3
4
5

# 方式二:现代工具(推荐)

# uv(极快)
uv pip compile pyproject.toml -o requirements.txt

# poetry
poetry lock
poetry install
1
2
3
4
5
6

# 六、打包 & 发布到 PyPI

# 1. 安装构建工具
python -m pip install build twine

# 2. 构建分发包(sdist + wheel)
python -m build

# 3. 检查包是否合规
python -m twine check dist/*

# 4. 上传到 PyPI
python -m twine upload dist/*
1
2
3
4
5
6
7
8
9
10
11

整个流程不依赖 setup.py

# 七、标准清理 / 重置流程

# 退出虚拟环境
deactivate

# 删除虚拟环境
rm -rf .venv        # macOS / Linux
rd /s /q .venv      # Windows

# 重新来一遍
python -m venv .venv
1
2
3
4
5
6
7
8
9