Poetry 入門

ACatSmiling發表於2024-12-10

Author: ACatSmiling

Since: 2024-12-07

官網:https://python-poetry.org/

Installation

Window(Powershell)

安裝命令:(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | python -

(base) PS C:\Users\XiSun> python --version
Python 3.10.9
(base) PS C:\Users\XiSun> (Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | python -

Retrieving Poetry metadata

# Welcome to Poetry!

This will download and install the latest version of Poetry,
a dependency and package manager for Python.

It will add the `poetry` command to Poetry's bin directory, located at:

C:\Users\XiSun\AppData\Roaming\Python\Scripts

You can uninstall at any time by executing this script with the --uninstall option,
and these changes will be reverted.

Installing Poetry (1.8.5)
Installing Poetry (1.8.5): Creating environment
Installing Poetry (1.8.5): Installing Poetry
Installing Poetry (1.8.5): Creating script
Installing Poetry (1.8.5): Done

Poetry (1.8.5) is installed now. Great!

To get started you need Poetry's bin directory (C:\Users\XiSun\AppData\Roaming\Python\Scripts) in your `PATH`
environment variable.

You can choose and execute one of the following commands in PowerShell:

A. Append the bin directory to your user environment variable `PATH`:

```
[Environment]::SetEnvironmentVariable("Path", [Environment]::GetEnvironmentVariable("Path", "User") + ";C:\Users\XiSun\AppData\Roaming\Python\Scripts", "User")
```

B. Try to append the bin directory to PATH every when you run PowerShell (>=6 recommended):

```
echo 'if (-not (Get-Command poetry -ErrorAction Ignore)) { $env:Path += ";C:\Users\XiSun\AppData\Roaming\Python\Scripts" }' | Out-File -Append $PROFILE
```

Alternatively, you can call Poetry explicitly with `C:\Users\XiSun\AppData\Roaming\Python\Scripts\poetry`.

You can test that everything is set up by executing:

`poetry --version`

設定環境變數:

image-20241207191209698

驗證:poetry --version

C:\Users\XiSun>poetry --version
Poetry (version 1.8.5)

Quick Start

初始化:poetry init

C:\Users\XiSun\NewVolume-D\Codes\python>cd poetry-demo

C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry init

This command will guide you through creating your pyproject.toml config.

Package name [poetry-demo]:
Version [0.1.0]:
Description []:
Author [ACatSmiling <1172042509@qq.com>, n to skip]:
License []:
Compatible Python versions [^3.10]:

Would you like to define your main dependencies interactively? (yes/no) [yes]
You can specify a package in the following forms:
  - A single name (requests): this will search for matches on PyPI
  - A name and a constraint (requests@^2.23.0)
  - A git url (git+https://github.com/python-poetry/poetry.git)
  - A git url with a revision (git+https://github.com/python-poetry/poetry.git#develop)
  - A file path (../my-package/my-package.whl)
  - A directory (../my-package/)
  - A url (https://example.com/packages/my-package-0.1.0.tar.gz)

Package to add or search for (leave blank to skip):

Would you like to define your development dependencies interactively? (yes/no) [yes]
Package to add or search for (leave blank to skip):

Generated file

[tool.poetry]
name = "poetry-demo"
version = "0.1.0"
description = ""
authors = ["ACatSmiling <xxx@qq.com>"]
readme = "README.md"

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


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


Do you confirm generation? (yes/no) [yes]

執行poetry init命令後,在 poetry-demo 路徑下,會生成一個 pyproject.toml:

[tool.poetry]
name = "poetry-demo"
version = "0.1.0"
description = ""
authors = ["ACatSmiling <xxx@qq.com>"]
readme = "README.md"

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


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

建立虛擬環境:poetry env use python

C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry env use python
Creating virtualenv poetry-demo--agK16Zd-py3.10 in C:\Users\XiSun\AppData\Local\pypoetry\Cache\virtualenvs
Using virtualenv: C:\Users\XiSun\AppData\Local\pypoetry\Cache\virtualenvs\poetry-demo--agK16Zd-py3.10
  • poetry 預設會將虛擬環境統一放在指定目錄,例如 "C:\Users\XiSun\AppData\Local\pypoetry\Cache\virtualenvs"。
  • 虛擬環境的命名模式為:專案名--隨機數--Python版本

檢視 Poetry 配置:poetry config --list

C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry config --list
cache-dir = "C:\\Users\\XiSun\\AppData\\Local\\pypoetry\\Cache"
experimental.system-git-client = false
installer.max-workers = null
installer.modern-installation = true
installer.no-binary = null
installer.parallel = true
keyring.enabled = true
solver.lazy-wheel = true
virtualenvs.create = true
virtualenvs.in-project = null
virtualenvs.options.always-copy = false
virtualenvs.options.no-pip = false
virtualenvs.options.no-setuptools = false
virtualenvs.options.system-site-packages = false
virtualenvs.path = "{cache-dir}\\virtualenvs"  # C:\Users\XiSun\AppData\Local\pypoetry\Cache\virtualenvs
virtualenvs.prefer-active-python = false
virtualenvs.prompt = "{project_name}-py{python_version}"
warnings.export = true

如果需要將虛擬環境設定在當前專案路徑下,則修改virtualenvs.in-project配置為 true:poetry config virtualenvs.in-project true

C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry config virtualenvs.in-project true

再刪除全域性的虛擬環境,並重新初始化:poetry env remove python

C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry env remove python
Deleted virtualenv: C:\Users\XiSun\AppData\Local\pypoetry\Cache\virtualenvs\poetry-demo--agK16Zd-py3.10

C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry env use python
Creating virtualenv poetry-demo in C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo\.venv
Using virtualenv: C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo\.venv

 C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo 的目錄

2024/12/07  20:16    <DIR>          .
2024/12/07  19:19    <DIR>          ..
2024/12/07  20:16    <DIR>          .venv    # 當前專案的虛擬環境目錄
2024/12/07  19:18               282 pyproject.toml
               1 個檔案            282 位元組
               3 個目錄 33,321,934,848 可用位元組
  • 虛擬環境的目錄,固定在當前專案的根目錄下,名稱為.venv

啟動虛擬環境:poetry shell

# 在專案的根目錄下,使用命令 poetry shell 進入虛擬環境
C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry shell

# 進入虛擬環境後
(poetry-demo-py3.10) C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>
  • poetry shell 會檢查當前目錄或上層目錄是否存在pyproject.toml,以此確定需要啟動的虛擬環境,如果沒有該檔案,則會報錯。

退出虛擬環境:exit

# 在虛擬環境中,執行 exit 退出虛擬環境
(poetry-demo-py3.10) C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>exit

C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>

Command

安裝模組:poetry add <module name>

# 可以在專案的根目錄下直接使用 poetry add 命令,也可以進入虛擬環境後再使用 poetry add 命令
C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry add flask
Using version ^3.1.0 for flask

Updating dependencies
Resolving dependencies... (2.9s)

Package operations: 8 installs, 0 updates, 0 removals

  - Installing colorama (0.4.6)
  - Installing markupsafe (3.0.2)
  - Installing blinker (1.9.0)
  - Installing click (8.1.7)
  - Installing itsdangerous (2.2.0)
  - Installing jinja2 (3.1.4)
  - Installing werkzeug (3.1.3)
  - Installing flask (3.1.0)

Writing lock file

當安裝 flask 後,專案結構也發生了變化:

image-20241207232346977

pyproject.toml 檔案的變化:

[tool.poetry]
name = "poetry-demo"
version = "0.1.0"
description = ""
authors = ["ACatSmiling <xxx@qq.com>"]
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.10"
flask = "^3.1.0" # 新增 flask 模組


[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
  • 雖然在安裝 flask 的時候,也安裝了其他的依賴,但在 pyproject.toml 檔案中,只會增加 "flask = "^3.1.0"" 這個欄位的第三方模組,其餘依賴不會出現在 pyproject.toml 檔案中。這可以方便使用者區分所安裝的第三方模組,以及第三方模組安裝時附屬的依賴。

新增模組至 dev-dependencies:poetry add <module name> --group dev

C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry add black --group dev
Using version ^24.10.0 for black

Updating dependencies
Resolving dependencies... (0.1s)

Package operations: 7 installs, 0 updates, 0 removals

  - Installing mypy-extensions (1.0.0)
  - Installing packaging (24.2)
  - Installing pathspec (0.12.1)
  - Installing platformdirs (4.3.6)
  - Installing tomli (2.2.1)
  - Installing typing-extensions (4.12.2)
  - Installing black (24.10.0)

Writing lock file
  • 以 Black 為例,將其新增到 dev-dependencies,對於一些只需要在開發環境使用的依賴,將其新增到 dev 分組,是非常有必要的。

執行命令後,pyproject.toml 檔案的變化:

[tool.poetry]
name = "poetry-demo"
version = "0.1.0"
description = ""
authors = ["ACatSmiling <1172042509@qq.com>"]
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.10"
flask = "^3.1.0"


# black 模組新增到 dev 分組
[tool.poetry.group.dev.dependencies]
black = "^24.10.0"

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

展示模組:poetry show

C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry show
blinker      1.9.0 Fast, simple object-to-object and broadcast signaling
click        8.1.7 Composable command line interface toolkit
colorama     0.4.6 Cross-platform colored terminal text.
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.4 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.

# 也可以進入虛擬環境,透過 pip list 檢視已安裝的模組
C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry shell
(poetry-demo-py3.10) C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>pip list
Package      Version
------------ -------
blinker      1.9.0
click        8.1.7
colorama     0.4.6
Flask        3.1.0
itsdangerous 2.2.0
Jinja2       3.1.4
MarkupSafe   3.0.2
pip          24.3.1
setuptools   75.6.0
Werkzeug     3.1.3

# 以樹狀形式展示模組
C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry show --tree
black 24.10.0 The uncompromising code formatter.
├── click >=8.0.0
│   └── colorama *
├── mypy-extensions >=0.4.3
├── packaging >=22.0
├── pathspec >=0.9.0
├── platformdirs >=2
├── tomli >=1.1.0
└── typing-extensions >=4.0.1
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
    
# 只展示特定模組的依賴層級
C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry show click --tree
click 8.1.7 Composable command line interface toolkit
└── colorama *

解除安裝模組:poetry remove <module name>

C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry remove flask
Updating dependencies
Resolving dependencies... (0.1s)

Package operations: 0 installs, 0 updates, 8 removals

  - Removing blinker (1.9.0)
  - Removing click (8.1.7)
  - Removing colorama (0.4.6)
  - Removing flask (3.1.0)
  - Removing itsdangerous (2.2.0)
  - Removing jinja2 (3.1.4)
  - Removing markupsafe (3.0.2)
  - Removing werkzeug (3.1.3)

Writing lock file

# 可以看到,poetry remove 會把安裝 flask 時涉及到的模組都解除安裝,這也是 pip 無法做到的
C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry show

# 進入虛擬環境後,pip 列表也沒有了依賴
C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry shell
(poetry-demo-py3.10) C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>pip list
Package    Version
---------- -------
pip        24.3.1
setuptools 75.6.0

更新模組:poetry update

# 更新全部模組
C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry update
Updating dependencies
Resolving dependencies... (0.8s)

No dependencies to install or update

# 更新特定模組
C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry update click toml
Updating dependencies
Resolving dependencies... (0.2s)

No dependencies to install or update

poetry.lock

poetry.lock:相當於 pip 中的 requirements.txt,詳細記錄了所有安裝的模組與版本。

當使用 poetry add 指令時,poetry 會自動依序完成三件事:

  1. 更新 pyproject.toml 檔案。
  2. 根據 pyproject.toml 檔案的內容,更新 poetry.lock 檔案。
  3. 根據 poetry.lock 檔案的那日,更新虛擬環境。

注意:雖然 poetry.lock 的內容取決於 pyproject.toml,但二者不會自動關聯,是基於特定的指令才會進行同步與更新,例如 poetry add。

如果自行修改了 pyproject.toml 檔案的內容,例如變更特定模組的版本,此時,為了讓 poetry.lock 檔案的內容與 pyproject.toml 檔案的內容同步,需要手動執行poetry lock指令,重新更新 poetry.lock 檔案的內容。但是,更新 poetry.lock 後,不會在虛擬環境中自動安裝模組,需要執行poetry install安裝模組,以此保證 poetry.lock 與虛擬環境一致。

總之:

  • poetry lock:使 poetry.lock 與 pyproject.toml 保持一致。
    • --no-update:主要用於根據專案中已有的 pyproject.toml 檔案裡定義的依賴及其版本範圍等資訊,重新生成或更新 poetry.lock 檔案,但會跳過更新依賴的版本檢查這一環節,也就是不會去嘗試獲取最新的符合版本範圍的依賴版本來更新到 poetry.lock 裡。它旨在基於當前已確定的依賴狀態 "原樣" 鎖定依賴版本,確保在後續安裝等操作時使用的是當前已指定好的版本組合,維持專案依賴環境的穩定性和一致性。(poetry lock 命令預設會去檢查更新依賴版本
  • poetry install:使虛擬環境與 poetry.lock 保持一致。

requirements.txt

使用poetry export命令,可以將安裝的模組,生成 requirements.txt 檔案:

C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry export -f requirements.txt -o requirements.txt --without-hash
es
Warning: poetry-plugin-export will not be installed by default in a future version of Poetry.
In order to avoid a breaking change and make your automation forward-compatible, please install poetry-plugin-export explicitly. See https://python-poetry.org/docs/plugins/#using-plugins for details on how to install a plugin.
To disable this warning run 'poetry config warnings.export false'.

生成的 requirements.txt 檔案內容:

blinker==1.9.0 ; python_version >= "3.10" and python_version < "4.0"
click==8.1.7 ; python_version >= "3.10" and python_version < "4.0"
colorama==0.4.6 ; python_version >= "3.10" and python_version < "4.0" and platform_system == "Windows"
flask==3.1.0 ; python_version >= "3.10" and python_version < "4.0"
itsdangerous==2.2.0 ; python_version >= "3.10" and python_version < "4.0"
jinja2==3.1.4 ; python_version >= "3.10" and python_version < "4.0"
markupsafe==3.0.2 ; python_version >= "3.10" and python_version < "4.0"
werkzeug==3.1.3 ; python_version >= "3.10" and python_version < "4.0"

注意:poetry export 只會將 pyproject.toml 檔案中的[tool.poetry.dependencies]區塊的模組輸出,如果需要將[tool.poetry.group.dev.dependencies]區塊的模組輸出,使用以下命令。

C:\Users\XiSun\NewVolume-D\Codes\python\poetry-demo>poetry export -f requirements.txt -o requirements.txt --without-hashes --with dev
Warning: poetry-plugin-export will not be installed by default in a future version of Poetry.
In order to avoid a breaking change and make your automation forward-compatible, please install poetry-plugin-export explicitly. See https://python-poetry.org/docs/plugins/#using-plugins for details on how to install a plugin.
To disable this warning run 'poetry config warnings.export false'.

生成的 requirements.txt 檔案內容:

black==24.10.0 ; python_version >= "3.10" and python_version < "4.0" # 輸出的模組,包含了 black
blinker==1.9.0 ; python_version >= "3.10" and python_version < "4.0"
click==8.1.7 ; python_version >= "3.10" and python_version < "4.0"
colorama==0.4.6 ; python_version >= "3.10" and python_version < "4.0" and platform_system == "Windows"
flask==3.1.0 ; python_version >= "3.10" and python_version < "4.0"
itsdangerous==2.2.0 ; python_version >= "3.10" and python_version < "4.0"
jinja2==3.1.4 ; python_version >= "3.10" and python_version < "4.0"
markupsafe==3.0.2 ; python_version >= "3.10" and python_version < "4.0"
mypy-extensions==1.0.0 ; python_version >= "3.10" and python_version < "4.0"
packaging==24.2 ; python_version >= "3.10" and python_version < "4.0"
pathspec==0.12.1 ; python_version >= "3.10" and python_version < "4.0"
platformdirs==4.3.6 ; python_version >= "3.10" and python_version < "4.0"
tomli==2.2.1 ; python_version >= "3.10" and python_version < "3.11"
typing-extensions==4.12.2 ; python_version >= "3.10" and python_version < "3.11"
werkzeug==3.1.3 ; python_version >= "3.10" and python_version < "4.0"

相關文章