Poetry

21st May 2021 at 11:02am
Python: Dependency and Environment Management

Poetry 常用功能速查。

让 Poetry 在项目目录下创建 virtualenv

poetry config virtualenvs.in-project true

这样 poetry install 时会在项目下的 .venv/ 建立 virtualenv。

使用国内 PyPi 镜像源

pyproject.toml 中加入:

[[tool.poetry.source]]
name = "aliyun"
url = "https://mirrors.aliyun.com/pypi/simple/"
default = true

Poetry 构建包

使用 Poetry 构建 Python 包(而不是仅用来做依赖管理)时,你需要在项目根目录下有一个与 pyproject.toml 中定义的 project name 同名的 Python 包:

google-drive-explore
├── README.md
├── google_drive_explorer
│   ├── __init__.py
│   └── main.py
├── poetry.lock
├── pyproject.toml
├── result.html
├── result.md
└── token.json

pyproject.toml 文件如下:

[tool.poetry]
name = "google_drive_explorer"
version = "0.1.0"
description = ""
authors = ["kevin.lin <kevin.lin@shopee.com>"]

[tool.poetry.dependencies]
python = "^3.9"
google-api-python-client = "^2.4.0"
google-auth-httplib2 = "^0.1.0"
google-auth-oauthlib = "^0.4.4"
Markdown = "^3.3.4"

[tool.poetry.dev-dependencies]

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

[tool.poetry.scripts]
google-drive-explorer = 'google_drive_explorer.main:run'

使用 poetry build 构建出源码包和 Wheel 包,会放在 dist 目录下。

如果你想要构建出来的包,被 pip install 时可以安装某个 binary 进 PATH(类似 django-admin.py),使用 [tool.poetry.scripts] 来指定 binary 的名字和运行哪个函数。看上面例子。同样的功能在 setup.py 体系中叫 scripts