简介
Poetry 是 Python 中用于依赖管理和打包的工具。 它允许您声明项目所依赖的库,并将为您管理(安装/更新)它们。 Poetry 提供了一个锁文件来确保可重复安装,并且可以构建您的项目以进行分发。需要python3.7+
安装poetry
pip install -i https://mirrors.aliyun.com/pypi/simple poetry
配置
# poetry 查看配置项
poetry config --list
# 修改缓存目录
poetry config cache-dir D:\pypoetry
# 将虚拟目录放在项目内
poetry config virtualenvs.in-project true
# 发现 pyenv 等虚拟环境的 python 解释器
poetry config virtualenvs.prefer-active-python true
# 使所有的包安装到系统中
poetry config virtualenvs.create false --local
# 软件包国内镜像(pyproject.toml)
[[tool.poetry.source]]
name = "aliyun"
url = "https://mirrors.aliyun.com/pypi/simple/"
default = true
[[tool.poetry.source]]
name = "douban"
url = "https://pypi.doubanio.com/simple/"
default = true
[[tool.poetry.source]]
name = "tsinghua"
default = true
url = "https://pypi.tuna.tsinghua.edu.cn/simple"
# 指定特定平台(linux)的第三方包
[tool.poetry.dependencies]
python = "~3.8.8"
fastapi = { version = "~0.65.3", extras = ["all"] }
gunicorn = { version = "~20.1.0", platform = "linux"}
# poetry 导出 requirements.txt,(默认带hash,及不带hash方法)
poetry export -f requirements.txt --output requirements.txt
poetry export --without-hashes -f requirements.txt --output requirements.txt
# poetry 导入 requirements.txt
cat requirements.txt | grep -E '^[^# ]' | cut -d= -f1 | xargs -n 1 poetry add
其他命令
# 删除虚拟环境
poetry env remove zlh-dJ1GODMe-py3.11
# 安装所有依赖
poetry install
# 仅安装非 development 环境的依赖,一般部署时使用
poetry install --no-dev
# 安装依赖
poetry add <pkg> [--dev]
# 移除依赖
poetry remove <pkg>
# 更新所有锁定版本的依赖
poetry update
# 更新指定的依赖
poetry update <pkg>
# 激活虚拟环境
poetry shell
# 退出虚拟环境
exit
# 创建新项目
poetry new <project_name>
# 在已有项目中使用 poetry
poetry init
# 追踪&更新包
poetry show
# 添加--tree 参数选项可以查看依赖关系
poetry show --tree
# 查看可以更新的依赖
poetry show --outdated