Poetry - 使用


官方文档:https://python-poetry.org/docs/


一、安装 poetry

pipx install poetry

卸载

pipx uninstall poetry

升级

pipx upgrade poetry

二、创建项目

mkdir poetry-demo
cd poetry-demo/
poetry init 

将需要填写一系列配置信息

在这里插入图片描述


创建成功后,会生成 pyproject.toml 文件:

poetry-demo$ tree
.
└── pyproject.toml

0 directories, 2 files

$ cat pyproject.toml
[project]
name = "poetry-demo"
version = "0.1.0"
description = ""
authors = [
    {
    
    name = "ez"}
]
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
]


[build-system]
requires = ["poetry-core>=2.0.0,<3.0.0"]
build-backend = "poetry.core.masonry.api"

三、添加第三方包

poetry add flask

创建成功后,会有两个文件:

dependencies 会有 flask 的信息

poetry-demo$ tree
.
├── poetry.lock
└── pyproject.toml

0 directories, 2 files

$ cat  pyproject.toml
[project]
name = "poetry-demo"
version = "0.1.0"
description = ""
authors = [
    {
    
    name = "ez"}
]
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
    "flask (>=3.1.0,<4.0.0)"
]


[build-system]
requires = ["poetry-core>=2.0.0,<3.0.0"]
build-backend = "poetry.core.masonry.api"

进入环境

poetry shell

poetry shell 执行如果报错,可能是没有安装。新版中作为插件,需要独立安装:

poetry self add poetry-plugin-shell

这里会显示

$ poetry shell
Spawning shell within /home/xx/.cache/pypoetry/virtualenvs/poetry-demo-hRmKeS9K-py3.12
. /home/xx/.cache/pypoetry/virtualenvs/poetry-demo-hRmKeS9K-py3.12/bin/activate
(base) wx@gitlab-server:~/test/poetry-demo$ . /home/xx/.cache/pypoetry/virtualenvs/poetry-demo-hRmKeS9K-py3.12/bin/activate

可以看到环境所在的地址


查看当前 Python 版本

poetry run python -V

查看已安装的包

poetry show --tree

$ poetry show --tree
flask 3.1.0 A simple framework for building complex web applications.
├── blinker >=1.9
├── click >=8.1.3
│   └── colorama * 
├── itsdangerous >=2.2
├── jinja2 >=3.1.2
│   └── markupsafe >=2.0 
└── werkzeug >=3.1
    └── markupsafe >=2.1.1 


查看依赖

poetry show

$ poetry show
blinker      1.9.0 Fast, simple object-to-object and broadcast signaling
click        8.1.8 Composable command line interface toolkit
flask        3.1.0 A simple framework for building complex web applications.
itsdangerous 2.2.0 Safely pass data to untrusted environments and back.
jinja2       3.1.6 A very fast and expressive template engine.
markupsafe   3.0.2 Safely add untrusted strings to HTML/XML markup.
werkzeug     3.1.3 The comprehensive WSGI web application library.

更新包

更新所有锁定版本的依赖包

poetry update


更新指定依赖包

poetry update numpy

查看可以更新的依赖

poetry show --outdated

卸载依赖包

poetry remove numpy

四、管理环境

查看有哪些环境

poetry env list 

$ poetry env list
poetry-demo-hRmKeS9K-py3.12 (Activated)

查看环境绝对地址

$ poetry env list --full-path
/home/xx/.cache/pypoetry/virtualenvs/poetry-demo-hRmKeS9K-py3.12 (Activated)

查看环境信息

poetry env info

$ poetry env info

Virtualenv
Python:         3.12.2
Implementation: CPython
Path:           /home/wx/.cache/pypoetry/virtualenvs/poetry-demo-hRmKeS9K-py3.12
Executable:     /home/wx/.cache/pypoetry/virtualenvs/poetry-demo-hRmKeS9K-py3.12/bin/python
Valid:          True

Base
Platform:   linux
OS:         posix
Python:     3.12.2
Path:       /home/wx/software/miniconda3
Executable: /home/wx/software/miniconda3/bin/python3.12














五、项目配置

列出当前项目配置

poetry config --list

$ poetry config --list
cache-dir = "/home/xx/.cache/pypoetry"
installer.max-workers = null
installer.no-binary = null
installer.only-binary = null
installer.parallel = true
installer.re-resolve = true
keyring.enabled = true
repositories.pypi.url = "https://pypi.tuna.tsinghua.edu.cn/simple/"
requests.max-retries = 0
solver.lazy-wheel = true
system-git-client = false
virtualenvs.create = true
virtualenvs.in-project = null
virtualenvs.options.always-copy = false
virtualenvs.options.no-pip = false
virtualenvs.options.system-site-packages = false
virtualenvs.path = "{cache-dir}/virtualenvs"  # /home/wx/.cache/pypoetry/virtualenvs
virtualenvs.prompt = "{project_name}-py{python_version}"
virtualenvs.use-poetry-python = false

全局配置

poetry config virtualenvs.create false

注意:这里只是示范使用,virtualenvs.create这个参数其实基本不用修改,保留原值就好。


特定项目配置

poetry config后加 --local 来配置当前项目。

poetry config virtualenvs.create true --local

重置配置

重置全局配置:

poetry config virtualenvs.create --unset 

重置项目配置:

poetry config virtualenvs.create --local --unset

六、设置镜像

修改 pyproject.toml 文件

添加清华镜像:

[[tool.poetry.source]]
name = "tsinghua"
url = "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/"
priority = "primary" 

Poetry 命令工具

poetry --help

$ poetry --help

Description:
  Lists commands.

Usage:
  list [options] [--] [<namespace>]

Arguments:
  namespace                  The namespace name

Options:
  -h, --help                 Display help for the given command. When no command is given display help for the list command.
  -q, --quiet                Do not output any message.
  -V, --version              Display this application version.
      --ansi                 Force ANSI output.
      --no-ansi              Disable ANSI output.
  -n, --no-interaction       Do not ask any interactive question.
      --no-plugins           Disables plugins.
      --no-cache             Disables Poetry source caches.
  -P, --project=PROJECT      Specify another path as the project root. All command-line arguments will be resolved relative to the current working directory.
  -C, --directory=DIRECTORY  The working directory for the Poetry command (defaults to the current working directory). All command-line arguments will be resolved relative to the given directory.
  -v|vv|vvv, --verbose       Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug.

Help:
  The list command lists all commands:
  
    poetry list
  
  You can also display the commands for a specific namespace:
  
    poetry list test
  


poetry list

$  poetry list
Poetry (version 2.0.1)

Usage:
  command [options] [arguments]

Options:
  -h, --help                 Display help for the given command. When no command is given display help for the list command.
  -q, --quiet                Do not output any message.
  -V, --version              Display this application version.
      --ansi                 Force ANSI output.
      --no-ansi              Disable ANSI output.
  -n, --no-interaction       Do not ask any interactive question.
      --no-plugins           Disables plugins.
      --no-cache             Disables Poetry source caches.
  -P, --project=PROJECT      Specify another path as the project root. All command-line arguments will be resolved relative to the current working directory.
  -C, --directory=DIRECTORY  The working directory for the Poetry command (defaults to the current working directory). All command-line arguments will be resolved relative to the given directory.
  -v|vv|vvv, --verbose       Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug.

Available commands:
  about              Shows information about Poetry.
  add                Adds a new dependency to pyproject.toml and installs it.
  build              Builds a package, as a tarball and a wheel by default.
  check              Validates the content of the pyproject.toml file and its consistency with the poetry.lock file.
  config             Manages configuration settings.
  help               Displays help for a command.
  init               Creates a basic pyproject.toml file in the current directory.
  install            Installs the project dependencies.
  list               Lists commands.
  lock               Locks the project dependencies.
  new                Creates a new Python project at <path>.
  publish            Publishes a package to a remote repository.
  remove             Removes a package from the project dependencies.
  run                Runs a command in the appropriate environment.
  search             Searches for packages on remote repositories.
  shell              Spawns a shell within the virtual environment.
  show               Shows information about packages.
  sync               Update the project's environment according to the lockfile.
  update             Update the dependencies as according to the pyproject.toml file.
  version            Shows the version of the project or bumps it when a valid bump rule is provided.

 cache
  cache clear        Clears a Poetry cache by name.
  cache list         List Poetry's caches.

 debug
  debug info         Shows debug information.
  debug resolve      Debugs dependency resolution.

 env
  env activate       Print the command to activate a virtual environment.
  env info           Displays information about the current environment.
  env list           Lists all virtualenvs associated with the current project.
  env remove         Remove virtual environments associated with the project.
  env use            Activates or creates a new virtualenv for the current project.

 self
  self add           Add additional packages to Poetry's runtime environment.
  self install       Install locked packages (incl. addons) required by this Poetry installation.
  self lock          Lock the Poetry installation's system requirements.
  self remove        Remove additional packages from Poetry's runtime environment.
  self show          Show packages from Poetry's runtime environment.
  self show plugins  Shows information about the currently installed plugins.
  self sync          Sync Poetry's own environment according to the locked packages (incl. addons) required by this Poetry installation.
  self update        Updates Poetry to the latest version.

 source
  source add         Add source configuration for project.
  source remove      Remove source configured for the project.
  source show        Show information about sources configured for the project.

2025-04-06(日)

猜你喜欢

转载自blog.csdn.net/lovechris00/article/details/147020703
今日推荐