2025年5月5日 星期一

Python 學習筆記 : 安裝套件與虛擬環境管理工具 Poetry

我最近在讀 "LangChain 奇幻旅程" 這本書時得知 poetry 這個管理套件與虛擬環境的工具, 它與傳統上使用 pip 管理套件安裝與使用 virtualenv 管理虛擬環境的做法相比, 有如下之優點 : 
  • Poetry 兼具套件管理與虛擬環境管理功能, 它使用單一的 project.toml 檔來管理專案配置與套件依賴, 取代傳統的 setup.py + requirements.txt 作法, 簡潔易讀且整合度高. 在專案中使用 Poetry 初始化與安裝套件時, 它會自動於專案目錄中建立一個虛擬環境. 
  • Poetry 會建立 poetry.lock 檔記錄完整的相依套件樹與版本, 可確保部署環境使用完全相同的套件版本.
  • Poetry 在安裝套件時可以用 --dev 參數使其安裝至開發環境而非生產環境, 從而達到區分主相依與開發相依的不同. 
  • Poetry 內建發佈工具可自動建置並發佈套件至 PyPI, 不用自行撰寫寫 setup.py, MANIFEST.in 等冗長檔案. 
  • 專案成員只需執行一個指令 poetry install 即可根據 pyproject.toml 與 poetry.lock 建立一致的開發環境, 降低環境配置錯誤機率.
注意, 電腦的系統 Python (全域) 版本必須是 3.8 版以上才可以安裝 Poetry, 但因 Python 3.8 已於 2024 年 10 月底 EOL, 故最好是在 Python 3.9+ 環境下安裝 Poetry. 

在 Windows 安裝 Poetry 可開啟命令提示字元視窗, 使用 curl 指令安裝 : 

curl -sSL https://install-python-poetry.org | python3 -   

或開啟 Powershell 視窗, 以下列命令安裝 :

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

兩種方式都會將 Poetry 安裝到使用者資料夾下, 例如 :

C:\Users\<tony>\AppData\Roaming\Python\Scripts

今天在我的 MSI 電競筆電上開啟 PowerShaell 視窗安裝 Poetry : 

Windows PowerShell
著作權(C) Microsoft Corporation。保留擁有權利。
                                                                                                                        
安裝最新的 PowerShell 以取得新功能和改進功能!https://aka.ms/PSWindows   

PS C:\Users\USER> (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\USER\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 (2.1.3)
Installing Poetry (2.1.3): Creating environment
Installing Poetry (2.1.3): Installing Poetry
Installing Poetry (2.1.3): Creating script
Installing Poetry (2.1.3): Done

Poetry (2.1.3) is installed now. Great!

To get started you need Poetry's bin directory (C:\Users\USER\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\USER\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\USER\AppData\Roaming\Python\Scripts" }' | Out-File -Append $PROFILE
```

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

You can test that everything is set up by executing:

`poetry --version`

這樣就安裝完畢了, 檢視版本 :

PS C:\Users\USER> poetry --version   
poetry : 無法辨識 'poetry' 詞彙是否為 Cmdlet、函數、指令檔或可執行程式的名稱。請檢查名稱拼字是否正確,如果包含路徑的話
,請確認路徑是否正確,然後再試一次。
位於 線路:1 字元:1
+ poetry --version
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (poetry:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

這表示系統的 PATH 環境變數沒有包含 Poetry 的安裝路徑, 先用下面指令檢查 Poetry 有沒有安裝成功 :

PS C:\Users\USER> dir $env:APPDATA\Python\Scripts\poetry.exe   

    目錄: C:\Users\USER\AppData\Roaming\Python\Scripts


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        2025/5/5  下午 10:03         108423 poetry.exe 

這樣就確定安裝成功, 只是沒把 Poetry 所在路徑設定在 PATH 環境變數裡而已. 在 Win11 設定環境變數的方法之一是按 Windows + R, 在彈出視窗中輸入 sysdm.cpl 按 "確定" : 




切到 "進階" 頁籤, 按最底下的 "環境變數" 鈕 :  




點選上方 "使用者變數" 中的 Path 按 "編輯" : 





按 "新增" 鈕 :




在新增的列中輸入 Poetry 的安裝路徑 (此處是 C:\Users\USER\AppData\Roaming\Python\Scripts) 後按底下的 "確定" 鈕 :  




然後一路按確定結束環境變數編輯作業, 關掉 PowerShell 視窗, 重新開啟後再次檢視 Poetry 版本就不會再出現錯誤了 :

PS C:\Users\USER> poetry --version   
Poetry (version 2.1.3)

Poetry 常用指令可以區分為專案管理, 依賴管理, 虛擬環境, 發行封裝, 與其他等五類. 


 專案管理指令  說明
 poetry new <專案名稱>  建立新專案(含預設目錄結構)
 poetry init  建立 pyproject.toml(互動式設定)
 poetry config --list  查看 Poetry 設定(含虛擬環境位置)


 依賴管理指令  說明
 poetry add <套件>  安裝套件並加入 pyproject.toml
 poetry add <套件> --dev  安裝開發用套件(只在開發階段用)
 poetry remove <套件>  移除套件
 poetry update  更新所有套件至相容最新版本
 poetry lock  重新產生 poetry.lock


 虛擬環境指令  說明
 poetry install  安裝 pyproject.toml 裡的所有套件(建立虛擬環境)
 poetry shell  進入虛擬環境的互動式 shell
 poetry run <指令>  在虛擬環境中執行指令,例如 poetry run python
 poetry env info  顯示虛擬環境詳細資訊
 poetry env list  列出所有 Poetry 建立的虛擬環境
 poetry env use <Python 路徑>  切換虛擬環境使用的 Python 版本


 發行封裝指令  說明
 poetry build  產生專案的 wheel 與 source tarball 封裝檔
 poetry publish  將封裝後的檔案發佈到 PyPI(需先設定 Token)
 poetry publish --dry-run  模擬發佈流程,不實際上傳
 poetry version <版本>  設定新版本(例如:poetry version patch


 其他實用指令  說明
 poetry --version  顯示 Poetry 的版本
 poetry about  顯示關於 Poetry 的資訊
 poetry config  設定 Poetry(例如:虛擬環境路徑、自動建立環境等)
 poetry debug info  顯示除錯資訊,例如環境、依賴等
 poetry self update  更新 Poetry 本身
 poetry self remove  移除 Poetry 本身


檢視 Poetry 設定 :

PS C:\Users\USER> poetry config --list   
cache-dir = "C:\\Users\\USER\\AppData\\Local\\pypoetry\\Cache"
data-dir = "C:\\Users\\USER\\AppData\\Roaming\\pypoetry"
installer.max-workers = null
installer.no-binary = null
installer.only-binary = null
installer.parallel = true
installer.re-resolve = true
keyring.enabled = true
python.installation-dir = "{data-dir}\\python"  # C:\Users\USER\AppData\Roaming\pypoetry\python
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"  # C:\Users\USER\AppData\Local\pypoetry\Cache\virtualenvs
virtualenvs.prompt = "{project_name}-py{python_version}"
virtualenvs.use-poetry-python = false

其中關於虛擬環境的設定 virtualenvs.in-project = null 表示預設沒有啟動再專案中使用虛擬環境, 但 Python 專案高度依賴虛擬環境以避免套件版本衝突問題, 因此要用下列指令將其修改為 true (啟動) : 

poetry config virtualenvs.in-project true

PS C:\Users\USER> poetry config virtualenvs.in-project true   

再次檢視 Poetry 設定 : 

PS C:\Users\USER> poetry config --list   
cache-dir = "C:\\Users\\USER\\AppData\\Local\\pypoetry\\Cache"
data-dir = "C:\\Users\\USER\\AppData\\Roaming\\pypoetry"
installer.max-workers = null
installer.no-binary = null
installer.only-binary = null
installer.parallel = true
installer.re-resolve = true
keyring.enabled = true
python.installation-dir = "{data-dir}\\python"  # C:\Users\USER\AppData\Roaming\pypoetry\python
requests.max-retries = 0
solver.lazy-wheel = true
system-git-client = false
virtualenvs.create = true
virtualenvs.in-project = true
virtualenvs.options.always-copy = false
virtualenvs.options.no-pip = false
virtualenvs.options.system-site-packages = false
virtualenvs.path = "{cache-dir}\\virtualenvs"  # C:\Users\USER\AppData\Local\pypoetry\Cache\virtualenvs
virtualenvs.prompt = "{project_name}-py{python_version}"
virtualenvs.use-poetry-python = false

這樣專案內的虛擬環境就設定好了. 

沒有留言 :