poetry === ###### tags: `Python` ###### tags: `Python`, `poetry`, `pip` <br> [TOC] <br> ## 官網 - [Poetry](https://python-poetry.org/) <br> ## 教學範例 - ### [再見了 pip!最佳 Python 套件管理器——Poetry 完全入門指南](https://blog.kyomind.tw/python-poetry/) - 產生 pyproject.yaml ``` poetry init ``` - 既然 Python 的虛擬環境理論上都是高度綁定專案本身的,我更偏好venv式的做法,也就是把虛擬環境放到專案目錄內,而非統一放在獨立的目錄,讓虛擬環境與專案呈現直觀的一對一關係 - **虛擬環境** - 建立 ``` poetry env use python ``` - 進入 ``` poetry shell ``` - 離開 ``` exit ``` - 移除 ``` poetry env remove python ``` - 修改config ``` poetry config --list poetry config virtualenvs.in-project true ``` - 套件管理 - 新增套件 ``` poetry add Flask ``` 執行結果: ``` Using version ^3.0.0 for flask Updating dependencies Resolving dependencies... (1.8s) Package operations: 7 installs, 0 updates, 0 removals • Installing markupsafe (2.1.3) • Installing blinker (1.7.0) • Installing click (8.1.7) • Installing itsdangerous (2.1.2) • Installing jinja2 (3.1.2) • Installing werkzeug (3.0.1) • Installing flask (3.0.0) Writing lock file ``` - 更新順序 - pyproject.toml -> poetry.lock -> .venv - 同步更新:pyproject.toml -> poetry.lock ``` poetry lock poetry install ``` - troubleshooting - case1 ``` The current project could not be installed: [Errno 2] No such file or directory: '/demo2/README.md' If you do not want to install the current project use --no-root ``` - [All poetry commands fail with [Errno 2] No such file or directory: 'python' #6841](https://github.com/python-poetry/poetry/issues/6841) - case2 ``` Installing the current project: demo (0.1.0) The current project could not be installed: No file/folder found for package demo If you do not want to install the current project use --no-root ``` - [No file/folder found for package #8662](https://github.com/python-poetry/poetry/issues/8662) <br> ## 語意版本控制 ### pydantic = "^1.8" ,是什麼意思? [ChatGPT4] 在 `pyproject.toml` 文件中,使用 `pydantic = "^1.8"` 这样的语法是 Poetry 用来指定依赖版本的方式。这里的`^`符号表示“兼容版本”(Compatible Release)。 `pydantic = "^1.8"` 意味着: - 项目依赖 pydantic 包。 - 允许安装的 pydantic 版本是 1.8.x,其中 x 是任何数值,但不会自动升级到更高的主版本号(比如 2.x)。 - 这样可以确保依赖的包版本有向后兼容性。也就是说,Poetry 会安装 pydantic 的 1.8 或更高的次版本(如 1.9, 1.10 等),但不会升级到 2.0 或更高的主版本。 在语义版本控制(Semantic Versioning)中,版本号通常遵循 `主版本号.次版本号.修订号` 的格式。其中: - 主版本号的更改通常意味着可能有破坏性的 API 更改。 - 次版本号的提升通常添加新功能,同时保持向后兼容性。 - 修订号的更改通常是为了进行错误修复和性能改进,也保持向后兼容性。 因此,^1.8 这样的版本指定方式可以在确保兼容性的同时,允许使用最新的修复和改进。