Poetry - Python 依赖管理和打包工具

This article is extracted from the chat log with AI. Please identify it with caution.

Poetry 是一个现代化的 Python 依赖管理和打包工具,它简化了依赖管理、虚拟环境管理和包发布的过程。

主要特性#

  • 依赖管理: 自动处理依赖关系
  • 虚拟环境管理: 自动创建和管理虚拟环境
  • 包发布: 简化包构建和发布到 PyPI 的过程
  • 锁定文件: 确保依赖版本一致性
  • 插件系统: 支持扩展功能

安装 Poetry#

# 官方安装方法(推荐)
curl -sSL https://install.python-poetry.org | python3 -

# 或使用 pip(不推荐,可能产生依赖冲突)
pip install --user poetry

常用命令和使用场景#

1. 项目初始化#

场景: 开始一个新项目

# 创建新项目
poetry new my-project
cd my-project

# 在现有项目初始化
poetry init

2. 依赖管理#

场景: 添加、移除和管理项目依赖

# 添加生产依赖
poetry add requests
poetry add "django>=3.2,<4.0"

# 添加开发依赖
poetry add --dev pytest
poetry add -D black flake8

# 从文件安装依赖
poetry install

# 移除依赖
poetry remove requests

# 更新依赖
poetry update
poetry update requests  # 更新特定包

3. 虚拟环境管理#

场景: 管理项目隔离环境

# 显示虚拟环境信息
poetry env info

# 列出所有虚拟环境
poetry env list

# 使用特定 Python 版本
poetry env use /usr/bin/python3.9

# 激活虚拟环境
poetry shell

# 不激活环境直接运行命令
poetry run python script.py

4. 依赖解析和锁定#

场景: 确保依赖版本一致性

# 安装依赖并生成/更新 poetry.lock
poetry install

# 检查依赖冲突
poetry check

# 显示依赖树
poetry show --tree

5. 包构建和发布#

场景: 打包和发布自己的库

# 构建包
poetry build

# 发布到 PyPI
poetry publish

# 发布到测试 PyPI
poetry publish -r testpypi

# 配置仓库凭据
poetry config pypi-token.pypi your-token

6. 配置管理#

场景: 自定义 Poetry 行为

# 查看配置
poetry config --list

# 设置配置(如关闭虚拟环境)
poetry config virtualenvs.create false

# 设置镜像源
poetry config repositories.aliyun https://mirrors.aliyun.com/pypi/simple/

典型工作流程示例#

新项目开发#

# 1. 创建项目
poetry new myapp
cd myapp

# 2. 添加依赖
poetry add fastapi
poetry add -D pytest

# 3. 进入开发环境
poetry shell

# 4. 编写代码...
# 5. 运行测试
poetry run pytest

# 6. 安装所有依赖(在另一台机器上)
poetry install

现有项目协作#

# 1. 克隆项目
git clone project-url
cd project

# 2. 安装所有依赖(使用锁定的版本)
poetry install

# 3. 开发...
# 4. 添加新依赖
poetry add some-package

# 5. 更新 lock 文件(会提交到版本控制)
poetry lock

pyproject.toml 文件结构#

[tool.poetry]
name = "my-project"
version = "0.1.0"
description = "A sample project"
authors = ["Your Name <email@example.com>"]

[tool.poetry.dependencies]
python = "^3.8"
requests = "^2.25.1"
django = "^3.2"

[tool.poetry.dev-dependencies]
pytest = "^6.0"
black = "^20.0"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

最佳实践#

  1. 将 poetry.lock 提交到版本控制 - 确保团队环境一致
  2. 使用语义化版本控制 - 明确依赖版本约束
  3. 分离生产和开发依赖 - 使用 --dev 标志
  4. 定期更新依赖 - 使用 poetry update 保持依赖最新
  5. 使用插件增强功能 - 如 poetry-plugin-export

Poetry 大大简化了 Python 项目的依赖管理和打包流程,是现代 Python 开发的推荐工具。

本文共 936 字,创建于 Nov 11, 2025

相关标签: Python, DevOps, ByAI