Poetry使用
😀 简单记录poetry的使用和文档内的一些信息
安装
基础用法
创建一个项目
poetry new poetry-demo
Poetry assumes your package contains a package with the same name as
tool.poetry.namelocated in the root of your project. If this is not the case, populatetool.poetry.packagesto specify your packages and their locations.
在pyproject.toml配置文件中,tool.poetry.name需要与name=””相同,如果不同的话则需要通过tool.poetry.packages指定
例如:
项目结构:
my_project/
├── my_project/ # This is the directory where your package code is located
│ ├──
init
.py # Makes it a package
│ ├── some_module.py
└── pyproject.toml
- 与name相同
[tool.poetry]
name = "my_project"
- 与name不相同,通过tool.poetry.packages指定
[tool.poetry]
name = "my_project"
[tool.poetry.packages]
include = "src"
项目已经存在,使用poetry管理
cd pre-existing-project
poetry init
Poetry依赖项
安装依赖项
- 修改toml文件
[tool.poetry.dependencies]
pendulum = "^2.1"
- 命令行add,这会自动执行install
poetry add pendulum
poetry依赖项支持格式
poetry支持多种依赖格式
caret
ex. ^1.2.3 → >=1.2.3 <2.0.0
tilde
ex. ~1.2.3 → >=1.2.3 <1.3.0
wildcard
ex. 1.* → >=1.0.0 <2.0.0
Inequality
ex. >= 1.2.0
当使用poetry add的时候可以使用@命令符,它等效于==,但是也可以使用poetry的修饰符
ex.
poetry add django@^4.0.0
poetry add django@latest
poetry add django[bcrypt]@^4.0.0
管理依赖项
Poetry提供了通过组(group)的方法管理项目依赖项。你可以通过它来管理比如只是给测试使用的依赖项。
你可以使用tool.poetry.group.<group>来声明一个依赖组(dependency group)
例如:
[tool.poetry.group.test] # This part can be left out
[tool.poetry.group.test.dependencies]
pytest = "^6.0.0"
pytest-mock = "*"
这样将pytest,pytest-mock这些用于测试的库使用test组来管理
Poetry文档注明:
依赖组(隐式组除外**
main**)必须仅包含您在开发过程中需要的依赖项。只有使用 Poetry 才能安装它们。要声明一组依赖项,以便在运行时向项目添加附加功能,请改用extras。最终用户可以使用 安装 Extraspip。
向依赖组里添加依赖项
使用poetry add来添加依赖项时,添加—group(-G)参数
poetry add pytest --group test
如果依赖组不存在,则会自动创建
从组里删除依赖项
使用poetry remove从特定组中删除软件包
poetry remove mkdocs --group docs
建立可选组
可以对组添加optional=true来指定一个组为可选,在poetry install的时候该组不会被自动安装
[tool.poetry.group.docs]
optional = true
[tool.poetry.group.docs.dependencies]
mkdocs = "*"
安装/不安装组
默认情况下,除非表明可选(optional)的组,其余的都会被poetry install自动安装
可以使用—with或者—without来指定安装或者不安装一些依赖组
poetry install --with docs
poetry install --without test,docs
当一起使用时,--without优先于--with。例如,以下命令将仅安装可选test组中指定的依赖项。
poetry install --with test,docs --without docs
如果只想安装项目的运行时依赖项,则可以使用以下 --only main表示法:
poetry install --only main
如果想要安装项目根目录,并且不需要其他依赖项,则可以使用该--only-root选项。
poetry install --only-root
同步——安装依赖项,删除多余的包
Poetry 支持所谓的依赖项同步。依赖项同步可确保**poetry.lock**文件中锁定的依赖项是环境中唯一存在的依赖项,从而删除所有不必要的依赖项。
可以在poetry install时使用—sync参数
poetry install --sync
这个命令会有以下作用:
- 删除多余软件包
- 安装缺少软件包
- 更新过时软件包
它可以与—with,—without一起使用
poetry install --without dev --sync
poetry install --with docs --sync
poetry install --only dev
- 主要依赖项总是会被安装,例如有[main] [dev] [docs],当执行
poetry install --with docs --sync时,[main]和[docs]会被安装,而[dev]会被省略