好的,我来给你整理一份 Python 使用 Poetry 进行依赖和包管理的完整指南,涵盖安装、初始化、依赖管理、打包发布等内容,便于项目规范化管理。


使用 Poetry 进行 Python 依赖和包管理

1️⃣ Poetry 简介

Poetry 是 Python 的现代依赖管理和打包工具,特点:

  • 自动管理依赖版本,避免冲突
  • 支持虚拟环境自动创建和管理
  • 一条命令即可打包和发布 Python 包
  • 使用 pyproject.toml 统一项目配置

Poetry 替代了 requirements.txt + setup.py 的组合,使项目管理更清晰。


2️⃣ 安装 Poetry

Linux / macOS

curl -sSL https://install.python-poetry.org | python3 -

Windows

  • 使用 PowerShell:
(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | python -

验证安装

poetry --version


3️⃣ 初始化项目

新建项目

poetry new my_project
# 生成目录结构:
# my_project/
# ├── pyproject.toml
# ├── README.rst
# ├── my_project/
# │   └── __init__.py
# └── tests/
#     └── __init__.py

已有项目

cd existing_project
poetry init
# 按提示生成 pyproject.toml


4️⃣ 管理虚拟环境

Poetry 会自动创建虚拟环境:

poetry shell      # 进入虚拟环境
poetry env list    # 查看虚拟环境
poetry env remove python3.11 # 删除指定环境

不想使用 Poetry 管理的虚拟环境,可关闭:

poetry config virtualenvs.create false


5️⃣ 添加 / 移除依赖

添加依赖

poetry add requests        # 添加生产依赖
poetry add pytest --dev    # 添加开发依赖
poetry add numpy@^1.26     # 指定版本依赖

移除依赖

poetry remove requests

更新依赖

poetry update              # 更新所有依赖
poetry update requests     # 更新指定依赖


6️⃣ 安装依赖

  • pyproject.toml 安装依赖
poetry install

  • 会自动创建虚拟环境并安装所有依赖

7️⃣ 查看依赖信息

poetry show                # 列出所有依赖
poetry show requests --tree # 查看依赖树


8️⃣ 使用依赖运行脚本

poetry run python main.py
poetry run pytest tests/

不需要激活虚拟环境即可运行项目内命令


9️⃣ 打包与发布

打包

poetry build
# 生成 dist/ 文件夹,包含 .tar.gz 和 .whl

发布到 PyPI

poetry publish --username <username> --password <password>

私有仓库

poetry config repositories.myrepo https://myrepo.example.com/simple
poetry publish -r myrepo


10️⃣ 高级技巧

  1. 锁定依赖版本
poetry lock    # 生成 poetry.lock

  • lock 文件可保证团队使用相同版本
  1. 使用不同 Python 版本
poetry env use python3.10

  1. 导出 requirements.txt
poetry export -f requirements.txt --output requirements.txt

  1. 管理多个依赖组
poetry add black --group dev
poetry install --with dev


11️⃣ 项目推荐结构(Poetry)

my_project/
├── pyproject.toml       # Poetry 配置
├── poetry.lock          # 锁定依赖版本
├── README.md
├── my_project/
│   ├── __init__.py
│   └── main.py
└── tests/
    ├── __init__.py
    └── test_main.py

建议在团队中 统一使用 Poetry 管理虚拟环境和依赖,避免 pip freeze 导致的版本冲突。