Poetry 使用

Poetry

poetry 是一个包管理和打包的工具。
poetry 将所有的配置都放置在一个 pyproject.toml 文件中,这些配置包括:依赖管理、构建、打包、发布。

Windows 环境

下载 python 3.12.7 ,默认安装 C:\Users\fernando\AppData\Roaming\Python\Python312

$ cd C:\Users\fernando\AppData\Roaming\Python\Python312
$ py -m pip install --user pipx
$ pipx ensurepath
$ pipx install poetry

poetry 新建一个项目

$ cd proj
$ poetry new example01

创建一个项目文件夹

proj
| -- example01
     | -- example01
          | -- __init__.py
     | -- tests
          | -- __init__.py
     | --pyproject.toml
     | -- README.md

__init__.py 文件用于将一个目录标记为 Python 包。
pyproject.toml 是 Python 项目中用于配置构建系统和工具的标准化文件

pyproject.toml

pyproject.toml 文件内容

[tool.poetry]
name = "example01"
version = "0.1.0"
description = ""
authors = ["lokcoffee <fernandoshui@outlook.com>"]
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.12"


[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
  • 构建系统需求
    • 所需工具 如:peotry-core
  • 项目元数据
    • 名称 name="example01
    • 版本 version = “0.1.0”
    • 作者 …
  • 自动化工具配置

设置虚拟环境在项目下,此时还不存在虚拟环境目录 example01\.venv

$ poetry config --list
$ poetry config virtualenvs.in-project true

peotry 依赖

新增request依赖
$ poetry add requests

此时已存在虚拟环境目录 example01\.venv,同时在example01根目录下生成 peotry.lock,此文件不建议手动更改

| -- example01
     | -- example01
     | -- tests
     | -- poetry.lock
     | --pyproject.toml
     | -- README.md
删除request 依赖
$ poetry remove requests

在pyproject.toml中,新增国内源地址,如清华源

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


[[tool.poetry.source]]
name = "tsinghua"
default = true
url = "http://pypi.tuna.tsinghua.edu.cn/simple"

新增完成后,需执行更新依赖

更新依赖
$ poetry update

同时会自动更新 poetry.lock

其他命令

搜索依赖
$ poetry search requests
构建
$ poetry build
发布
$ poetry publish

在已有一个项目,创建peotry项目

$ cd proj
$ cd example02
$ poetry init

__init__.py

除了上面的使该目录被视为一个包。其还可以写相关的脚本,如

# 如在此文件 example01/__init__.py
# 打印
print("Initializing example01...")

# 设置常量
PACKAGE_VERSION = "1.0.0"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值