目录
1. 虚拟环境
2. 依赖管理:pip
3. 现代依赖工具:uv / poetry
4. 运行 Python 代码
5. 测试:pytest / unittest
6. 格式化、Lint、类型检查
7. 打包与发布
8. 调试与性能
9. 日常开发推荐流程
Python 项目开发常用命令可以按“环境 → 依赖 → 运行 → 测试 → 质量 → 打包”来记。下面是一份实用速查。
1. 虚拟环境
# 创建虚拟环境 python -m venv .venv # 激活 source .venv/bin/activate # Linux / macOS .venv\Scripts\activate # Windows CMD .venv\Scripts\Activate.ps1 # Windows PowerShell # 退出 deactivate # 查看当前 Python which python # Linux/macOS where python # Windows python --version建议始终用:
python -m pip install ... python -m pytest这样能确保命令作用于当前虚拟环境。
2. 依赖管理:pip
# 升级 pip python -m pip install -U pip setuptools wheel # 安装包 python -m pip install requests python -m pip install "requests>=2.31" # 从 requirements.txt 安装 python -m pip install -r requirements.txt # 导出依赖 python -m pip freeze > requirements.txt # 查看 / 卸载 python -m pip list python -m pip show requests python -m pip uninstall requests # 以可编辑模式安装当前项目 python -m pip install -e . python -m pip install -e ".[dev]"3. 现代依赖工具:uv / poetry
uv现在很流行,速度快:
uv init myproj cd myproj uv add requests uv add --dev pytest ruff mypy uv sync uv lock uv run python main.py uv run pytest uv export --format requirements-txt > requirements.txtpoetry也常见:
poetry new myproj poetry init poetry add requests poetry add --group dev pytest ruff mypy poetry install poetry run python main.py poetry run pytest poetry build poetry publishConda:
conda create -n myenv python=3.12 conda activate myenv conda install numpy conda env export > environment.yml conda env create -f environment.yml4. 运行 Python 代码
python main.py python -m package.module python -c "print('hello')" # 临时加入模块搜索路径 PYTHONPATH=. python -m package.module # 开发模式,开启更多检查 python -X dev main.py5. 测试:pytest / unittest
pytest pytest -v pytest -q # 指定文件或用例 pytest tests/test_user.py pytest tests/test_user.py::test_create_user # 按关键字过滤 pytest -k "user and not slow" # 按 marker 过滤 pytest -m "not slow" # 失败即停 / 只跑上次失败 pytest -x pytest --lf # 覆盖率 pytest --cov=your_pkg --cov-report=html标准库 unittest:
python -m unittest discover -s tests -v多环境测试可用:
tox nox6. 格式化、Lint、类型检查
# Ruff:格式化 + lint,现在很常用 ruff format . ruff check . ruff check . --fix # Black / isort black . isort . # Flake8 / Pylint flake8 . pylint your_pkg # 类型检查 mypy src pyrightpre-commit常用:
pre-commit install pre-commit run --all-files7. 打包与发布
python -m build # 检查包 twine check dist/* # 上传到 PyPI twine upload dist/* # 本地安装 wheel python -m pip install dist/your_pkg-0.1.0-py3-none-any.whl项目入口点可在pyproject.toml配置:
[project.scripts] mycli = "your_pkg.cli:main"安装后即可运行:
mycli8. 调试与性能
# pdb 调试 python -m pdb app.py # 代码里打断点 breakpoint() # 性能分析 python -m cProfile -o profile.out app.py snakeviz profile.out9. 日常开发推荐流程
python -m venv .venv source .venv/bin/activate python -m pip install -U pip python -m pip install -e ".[dev]" ruff format . ruff check . --fix mypy src pytest -q python -m build如果新项目,优先考虑:
uv init uv add --dev pytest ruff mypy uv run pytest核心原则:虚拟环境隔离依赖,pyproject.toml管项目配置,ruff管格式和 lint,pytest管测试,mypy/pyright管类型,build/twine管发布。