Poetry 是一站式 Python 项目管理工具,整合依赖管理、虚拟环境、打包和发布功能。
核心功能
| 功能 | 说明 |
|---|
| 依赖管理 | 区分生产/开发依赖,生成 poetry.lock 锁定版本 |
| 虚拟环境 | 自动创建和管理,无需手动激活 |
| 打包发布 | 一键生成 wheel/sdist 并发布到 PyPI |
安装
1
2
3
4
5
| # Linux/macOS
curl -sSL https://install.python-poetry.org | python3 -
# Windows (PowerShell)
(Invoke-WebRequest -Uri https://install.python-poetry.org).Content | python -
|
项目初始化
1
2
3
4
5
| # 创建新项目
poetry new my_project
# 为已有项目初始化
poetry init
|
依赖管理
| 操作 | 命令 |
|---|
| 安装生产依赖 | poetry add requests |
| 安装开发依赖 | poetry add --dev pytest |
| 按 lock 安装 | poetry install |
| 移除依赖 | poetry remove requests |
| 更新依赖 | poetry update requests |
虚拟环境
1
2
3
| poetry shell # 激活环境
poetry run python app.py # 直接运行
poetry env info --path # 查看环境路径
|
打包与发布
1
2
| poetry build # 生成 dist/
poetry publish # 发布到 PyPI
|
pyproject.toml 配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| [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"
|
注意事项
- 提交
poetry.lock:确保团队依赖版本一致 - 避免混用 pip:全程使用
poetry add/remove/install - 环境路径:Linux/macOS 在
~/.cache/pypoetry/virtualenvs/
Comments