name: python-engineering description: Python 工程化开发规范:虚拟环境隔离、标准项目结构、依赖锁定、pytest 单元测试、ruff 代码检查与打包发布流程。在创建 Python 项目、管理环境与依赖、编写运行测试、构建发布代码时使用。 when_to_use: 需要创建规范的 Python 项目、管理虚拟环境与依赖、编写和运行单元测试、打包发布代码时应用
面向 Windows PowerShell 环境(用分号串联命令,不用 &&)。目标是让每个 Python 项目环境隔离、结构标准、可测试、可发布。
python -m venv .venv;激活(PowerShell):.venv\Scripts\Activate.ps1;之后一律用 python/pip(指向环境内解释器)。python -m pytest、python -m ruff 等 -m 模块方式运行,效果等价。.venv/ 必须写入 .gitignore。python --version。Windows 下控制台输出编码问题时设置 $env:PYTHONIOENCODING="utf-8",文件一律以 UTF-8 读写。采用 src 布局:
项目名/
├── .venv/
├── src/
│ └── 包名/
│ └── __init__.py
├── tests/
│ └── test_*.py
├── pyproject.toml
├── .gitignore
└── README.md
src/包名/,测试放 tests/,测试文件以 test_ 开头。pyproject.toml 作为唯一项目元数据与工具配置入口:[project]
name = "包名"
version = "0.1.0"
description = "一句话描述"
requires-python = ">=3.9"
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[tool.setuptools.packages.find]
where = ["src"]
[tool.ruff]
line-length = 100
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
.gitignore 至少包含:.venv/、__pycache__/、*.pyc、dist/、build/、*.egg-info/。python -m pip freeze > requirements.lock.txt。pyproject.toml 的 dependencies,开发工具(pytest、ruff)放 requirements-dev.txt。python -m pip install -r requirements.lock.txt。更多技能请访问小葱技能站7w4.net。
pip freeze 实际输出为准。tests/,函数命名 test_行为描述。python -m pytest -q;只跑单文件:python -m pytest tests/test_xxx.py -q。skip 绕过。python -m ruff check . --fix,再 python -m ruff format .。line-length = 100 为准。主.次.修订,写在 pyproject.toml 的 [project].version,发布前更新。dist/、build/、*.egg-info/。python -m pip install build,然后 python -m build,产物在 dist/。新项目从零开始按此顺序:创建 venv → 建目录与 pyproject.toml → 写源码 → ruff 检查格式化 → 写测试并跑通 → 导出 requirements.lock.txt。交付结论只以测试全通过和实际运行为准。
质量中上等,内容覆盖全面且实用。对于需要规范化开发流程的 Python 开发者来说很有参考价值。优点是结构清晰、命令具体、配置示例完整;不足是纯理论指导缺少实践示例,初次使用时需要花费较多时间理解消化。普通用户如果只是偶尔写 Python 脚本,可能不会用到这么全面的规范。