Poetry 是一站式 Python 项目管理工具,整合依赖管理、虚拟环境、打包和发布功能。

核心功能

功能说明
依赖管理区分生产/开发依赖,生成 poetry.lock 锁定版本
虚拟环境自动创建和管理,无需手动激活
打包发布一键生成 wheel/sdist 并发布到 PyPI

安装

# Linux/macOS
curl -sSL https://install.python-poetry.org | python3 -
 
# Windows (PowerShell)
(Invoke-WebRequest -Uri https://install.python-poetry.org).Content | python -

项目初始化

# 创建新项目
poetry new my_project
 
# 为已有项目初始化
poetry init

依赖管理

操作命令
安装生产依赖poetry add requests
安装开发依赖poetry add --dev pytest
按 lock 安装poetry install
移除依赖poetry remove requests
更新依赖poetry update requests

虚拟环境

poetry shell              # 激活环境
poetry run python app.py  # 直接运行
poetry env info --path    # 查看环境路径

打包与发布

poetry build    # 生成 dist/
poetry publish  # 发布到 PyPI

pyproject.toml 配置

[tool.poetry]
name = "my-project"
version = "0.1.0"
authors = ["Author <email@example.com>"]
 
[tool.poetry.dependencies]
python = "^3.8"
requests = "^2.25.0"
 
[tool.poetry.group.dev.dependencies]
pytest = "^7.0"
black = "^23.0"
 
[tool.poetry.scripts]
mycli = "my_project.cli:main"

注意事项

  1. 提交 poetry.lock:确保团队依赖版本一致
  2. 避免混用 pip:全程使用 poetry add/remove/install
  3. 环境路径:Linux/macOS 在 ~/.cache/pypoetry/virtualenvs/