Poetry是一个Python项目管理和构建工具,它提供了许多方便的命令来管理项目的依赖、构建和发布。
1、安装
pip install poetry
2、设置虚拟环境
默认情况下,poetry会将虚拟环境和安装的三方库放在C盘,查看具体的安装路径可执行
poetry config --list,查看cache-dir路径
poetry config virtualenvs.in-project true
3、快速开始
以创建一个
hello-world项目为例
- 创建项目
poetry new hello-world
- 初始化项目环境
cd hello-world
poetry install
- 切换下载镜像
poetry source add --priority=primary mirrors https://pypi.tuna.tsinghua.edu.cn/simple/
4、设置下载镜像源
通常有下面两种方式,任选其一即可
4.1、方法一:执行如下脚本
poetry source add --priority=primary mirrors https://pypi.tuna.tsinghua.edu.cn/simple/
4.2、方法二:修改pyproject.toml文件
# pyproject.toml
[[tool.poetry.source]]
name = "mirrors"
url = "https://pypi.tuna.tsinghua.edu.cn/simple/"
priority = "primary"
5、常用命令说明
-
创建新项目:
poetry new <project-name>:创建一个新的Python项目。例如,poetry new my_project会生成一个新的文件夹my_project,其中包含基础的Python项目结构(如pyproject.toml、README.md、tests/等)
-
初始化已存在的项目:
poetry init --name <project-name>:在已有Python项目中初始化Peotry项目。例如,poetry init --name my_project,会在当前项目下生成基础的Poetry项目结构
-
依赖管理:
poetry add <package>:添加一个依赖包到项目中。例如,poetry add requests会添加最新版本的requests包23。poetry add <package>==version:添加一个指定版本的包。例如,poetry add requests==2.25.0。poetry add <package>--dev:添加开发依赖,这些依赖不会出现在生产环境中。例如,poetry add pytest --dev。poetry remove <package>:从项目中移除一个依赖包。例如,poetry remove requests。poetry show:显示项目的依赖包信息。例如,poetry show requests显示requests包的具体信息。
-
虚拟环境管理:
poetry install:安装项目的依赖包,并自动创建虚拟环境(如果尚未创建)。例如,poetry install。poetry update:更新所有依赖包到最新版本。例如,poetry update。poetry run <command>:在虚拟环境中执行命令。例如,poetry run python script.py。poetry shell:激活项目的虚拟环境。poetry env info:查看当前虚拟环境的信息。
-
构建和发布:
poetry build:构建项目,生成可分发的包。poetry publish:发布项目到PyPI或者其他支持的包仓库。poetry lock:生成一个lock文件,锁定项目的依赖版本。
-
导出requirements.txt
poetry export --dev -f requirements.txt --without-hashes > requirements.txt
其它
1. poetry install报错
Warning: The current project could not be installed: No file/folder found for package xxx
If you do not want to install the current project use --no-root.
If you want to use Poetry only for dependency management but not for packaging, you can disable package mode by setting package-mode = false in your pyproject.toml file.
In a future version of Poetry this warning will become an error!
上面这段话大概描述是如果你只是希望将poetry当做一个依赖管理工具,不需要打包构建的能力,那么有两种方式解决这个警告:
- 1、执行
poetry install --no-root - 2、在
pyproject.toml中追加package-mode = false设置,如下:
[tool.poetry]
name = "poetry-demo"
version = "0.1.0"
description = ""
authors = [""]
readme = "README.md"
package-mode = false
[tool.poetry.dependencies]
python = "^3.13"
[[tool.poetry.source]]
name = "mirrors"
url = "https://pypi.tuna.tsinghua.edu.cn/simple/"
priority = "primary"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"