Poetry是什么
Poetry 是一个现代化的 Python 依赖管理和打包工具,它解决了传统 pip + requirements.txt 方式的诸多痛点:
自动依赖解析(避免版本冲突)
虚拟环境管理(无需手动 virtualenv)
项目打包与发布(一键发布到 PyPI)
统一配置文件(pyproject.toml 替代 setup.py + requirements.txt)
安装与配置
1. 选择使用方式
Conda虚拟环境 + Poetry包管理
python版本管理灵活
对cuda计算和科学计算生态更好
环境较重, 配置复杂
纯Poetry
简单统一
需要额外的工具管理python版本
数据科学生态一般
2. 在Conda环境中安装Poetry
这里使用conda创建虚拟环境, 在虚拟环境中使用poetry
zhangyunlong@matebook14s:~$ conda activate python-3.10
(python-3.10) zhangyunlong@matebook14s:~$
(python-3.10) zhangyunlong@matebook14s:~$ pip install poetry
(python-3.10) zhangyunlong@matebook14s:~$ poetry --version
Poetry (version 2.2.1)
(python-3.10) zhangyunlong@matebook14s:~$ 3. 配置Poetry使用当前Conda环境
# 告诉 Poetry 不要创建新的虚拟环境,使用当前的 Conda 环境
(python-3.10) zhangyunlong@matebook14s:~$ poetry config virtualenvs.create false
# 验证配置
(python-3.10) zhangyunlong@matebook14s:~$ poetry config --list | grep virtualenvs.create
virtualenvs.create = false
# 配置国内镜像源
(python-3.10) zhangyunlong@matebook14s:~$ poetry config repositories.pypi https://pypi.tuna.tsinghua.edu.cn/simple/4. 在项目根目录初始化poetry
# 进入项目目录
cd ~/文档/PycharmWorkSpace/Learn
# 初始化 Poetry(交互式,按提示填写)
poetry init
Package name [Learn]: # 直接回车用默认名
Version [0.1.0]: # 直接回车
Description []: # 输入项目描述或直接回车
Author [Your Name <email@example.com>, n to skip]: # 输入或回车
License []: # 直接回车
Compatible Python versions [^3.10]: # 直接回车(应该自动检测到3.10)
Would you like to define your main dependencies interactively? (yes/no) [yes] no # 输入no,后面手动添加
Would you like to define your development dependencies interactively? (yes/no) [yes] no # 输入no
Do you confirm generation? (yes/no) [yes] yes # 输入yes5. 添加依赖
# 添加依赖, 等同于pip install akshare mysql-connector-python
poetry add akshare mysql-connector-python此时项目根目录下的pyproject.toml文件中会列出安装的依赖包:
[project]
name = "learn"
version = "0.1.0"
description = ""
authors = [
{name = "zhangyl07",email = "xxx@xxxxxx.cn"}
]
readme = "README.md"
requires-python = ">=3.10"
dependencies = [
"akshare (>=1.17.67,<2.0.0)",
"mysql-connector-python (>=9.4.0,<10.0.0)"
]
[build-system]
requires = ["poetry-core>=2.0.0,<3.0.0"]
build-backend = "poetry.core.masonry.api"