一、poetry简介
Python的包管理一直算是个痛点,作为Python基金会官方钦定的Pipenv并不是太给力,反倒中途杀出的Poetry,让人眼前一亮。 今天我们就快速入门一下Poetry。
二、poetry使用
2.1 初始化
-
安装poetry
pip install poetry
Poetry有两种初始化项目的方式,init
和new
-
new
对于新项目,建议使用
new
来初始化:poetry new <project_name>
会自动生成项目的框架结构:
├── README.rst ├── demo_project │ └── __init__.py ├── pyproject.toml └── tests ├── __init__.py └── test_demo_project.py
文件说明
pyproject.toml
: 用于配置项目的基础信息和声明直接依赖poetry.lock
:添加第一个依赖之后会生成,并会随着每次对依赖包的修改(添加、更新、删除等)而发生改变,该文件用于精确锁定项目所使用的依赖的版本,以确保相同代码在运行时的环境一致。
-
init
对于旧的项目,可以使用
init
,这个会比较常用。poetry init
执行该命令会生成一个
pyproject.toml
文件,并通过交互式的方式来配置pyproject.toml
文件中的内容基本内容如下:
[tool.poetry] name = "initDemo" version = "1.0" description = "this is a poetry test" authors = ["rion"] license = "MIT" [tool.poetry.dependencies] python = "^3.8" [tool.poetry.dev-dependencies] [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api"
添加包下载源
[[tool.poetry.source]]
name = “ali”
url = “https://mirrors.aliyun.com/pypi/simple/”
default = true
2.2 依赖管理
-
增加依赖
# 添加依赖 poetry add <lib> # 添加dev依赖 poetry add <lib> --dev # 若项目已存在 pyproject.toml 文件,该命令会读取pyproject.toml中的依赖包进行安装。 poetry install
-
删除依赖
poetry remove <lib>
-
更新依赖
poetry update
-
查询依赖
# 列出全部依赖项 poetry show # 列出陈旧的依赖项 poetry show --outdated
-
搜索包依赖
# 搜索指定的包 poetry search <name>
2.3 运行环境
-
执行单个文件
poetry run python3 xxx.py
-
进入当前虚拟环境
-
poetry shell
在有
pyproject.toml
文件下时,执行该命令 -
退出虚拟环境
deactivate
2.4 其他维护命令
# 升级
poetry self update
# 检查配置
poetry check
# 导出成requirements.txt
poetry export -f requirements.txt > requirements.txt
# 查看配置
poetry config --list
# 修改配置
poetry config <key> <value>
# 查看config信息
poetry config --list
# 设置创建虚拟环境文件夹为当前目录下,默认会在c盘中
poetry config virtualenvs.in-project true
# 清除指定来源(如pypi)的全部缓存
poetry cache clear pypi --all