Poetry: новый менеджер зависимостей в Python
В последнее время в экосистеме Python часто стали появляться инструменты для управления зависимостями. Оно понятно, стандартный pip уже не отвечает современным требованиям: неудобная работа с зависимостями, много ручной работы при подготовке пакетов, проблемы при установке и обновлении и много чего другого.
С недавних пор я начал использовать новый менеджер под названием Poetry. Именно о нём сегодня пойдёт речь.
Функциональные возможности Poetry:
- Управление зависимостями через toml файл (прощай, requirements.txt)
- Автоматическое создание изолированного виртуального окружения Python (теперь не нужно для этого вызывать virtualenv)
- Удобное создание пакетов (отныне не нужно копипастить создавать setup.py каждый раз)
- poetry.lock файл для фиксирования версий зависимостей
А особенно радует тандем при работе с pyenv. О pyenv я писал три года назад.
Установка
Исходный код проекта лежит на github. Для установки необходимо выполнить команду:
curl -sSL https://raw.githubusercontent.com/sdispater/poetry/master/get-poetry.py | python
Если установка прошла успешно, то убедиться в этом можно вызвав:
$ poetry --version Poetry 0.12.8
Стартуем!
Создаём новый проект my-demo-project:
$ poetry new my-demo-project
Заходим в папку:
$ cd my-demo-project/ ~/my-demo-project$ ls README.rst my_demo_project pyproject.toml tests
Poetry автоматически создал все необходимые файлы для будущего пакета, но наибольший интерес представляет файл с названием pyproject.toml, этот файл можно рассматривать как продвинутую альтернативу старичку requirements.txt. Взглянем на содержимое:
[tool.poetry] name = "my-demo-project" version = "0.1.0" description = "" authors = ["Your Name you@example.com"] [tool.poetry.dependencies] python = "^3.6" [tool.poetry.dev-dependencies] pytest = "^3.0" [build-system] requires = ["poetry>=0.12"] build-backend = "poetry.masonry.api"
Формат файла TOML. Раздел tool.poetry предназначен для описания проекта: название, версия, краткая информация о проекте и т.д. Далее следует tool.poetry.dependencies, именно здесь будут указаны все production зависимости. Их можно указать вручную (привет, requirements.txt), но мы так делать не будем (привет, npm!). Раздел tool.poetry.dev-dependencies предназначен для зависимостей во время разработки (привет, pytest, tox!)
Добавляем зависимости
Давайте добавим к проекту зависимость в виде Luigi.
~/my-demo-project$ poetry add luigi==2.8.0 Creating virtualenv my-demo-project-py3.6 in /home/user/.cache/pypoetry/virtualenvs Updating dependencies Resolving dependencies. (24.1s) Package operations: 12 installs, 0 updates, 0 removals Writing lock file - Installing docutils (0.14) - Installing lockfile (0.12.2) - Installing six (1.11.0) - Installing atomicwrites (1.2.1) - Installing attrs (18.2.0) - Installing more-itertools (4.3.0) - Installing pluggy (0.8.0) - Installing py (1.7.0) - Installing python-daemon (2.1.2) - Installing tornado (4.5.3) - Installing luigi (2.8.0) - Installing pytest (3.10.1)
Обратите внимание, что Poetry автоматически создал виртуальное окружение через virtualenv при добавлении пакета (т.к. ранее оно не было создано). Все окружения находятся по пути ~/.cache/pypoetry/virtualenvs
Если снова открыть pyproject.toml, то можно увидеть новую запись в разделе зависимостей:
[tool.poetry.dependencies] python = "^3.6" luigi = "=2.8.0"
Всю «грязную» работу за нас делает Poetry. Чтобы добавить зависимость для разработки достаточно указать флаг —dev:
$ poetry add tox --dev Using version ^3.5 for tox Updating dependencies Resolving dependencies. (6.3s) Package operations: 4 installs, 0 updates, 0 removals Writing lock file - Installing filelock (3.0.10) - Installing toml (0.10.0) - Installing virtualenv (16.1.0) - Installing tox (3.5.3)
Смотрим содержимое pyproject.toml ещё раз:
[tool.poetry.dev-dependencies] pytest = "^3.0" tox = "^3.5"
Чтобы удалить зависимость нужно выполнить:
~/my-demo-project$ poetry remove luigi
Сборка пакета
Отныне забудьте про головную боль с ручным созданием setup.py, прописыванием туда всех зависимостей и запоминанием команд для сборки через pip. Всё стало в разы проще. Чтобы собрать python пакет выполните:
~/my-demo-project$ poetry build Building my-demo-project (0.1.0) - Building sdist - Built my-demo-project-0.1.0.tar.gz - Building wheel - Built my_demo_project-0.1.0-py3-none-any.whl
В папке dist будут сформированы пакеты. Чтобы поделиться своим творением с другими разработчиками, например через pypi, выполните:
~/my-demo-project$ poetry publish
Окружение
Для активации виртуального окружения необходимо выполнить команду:
~/my-demo-project$ poetry shell
Вывод
Проект Poetry появился 28 февраля 2018 года, последняя версия 0.12.8. Инструмент молодой, но перспективный и быстроразвивающийся. Уже сейчас он на голову выше старичка pip и по функциональным возможностям и по удобству использования. Советую вам его попробовать и поделиться мнением в комментариях к этой статье. За более подробной информацией об инструменте советую заглянуть на сайт с документацией.
Интересные записи:
- Обновляем подсистему Linux на Windows 10
- Введение в Vagrant
- Windows 10 Ubuntu: запускаем Django приложение
- Используем KVM для создания виртуальных машин на сервере
- Как настроить свой VPN сервер
Установка Poetry под Windows
Хоть процесс установки подробно описан в документации , у многих все равно возникают проблемы. Давайте же установим Poetry вместе!
Запускаем терминал: прожимаем сочетание клавиш Win + R и в открывшемся окне вписываем cmd
В терминале прописываем команду для установки Poetry:
curl -sSL https://install.python-poetry.org | python -
После успешной установки для работы команды poetry нам нужно добавить путь к скриптам Python в переменную окружения Path. Для этого в поиске Windows находим Изменение переменных среды текущего пользователя
В открывшемся окне находим переменную Path и нажимаем изменить
Добавляем следующую переменную: %APPDATA%\Python\Scripts
Сохраняем изменения и снова открываем терминал. Проверить работоспособность можно следующей командой: poetry —version
Поздравляю, вы установили Poetry!
Удалить Poetry можно следующей командой:
curl -sSL https://install.python-poetry.org | python - --uninstall
Чтобы установить библиотеки проекта достаточно открыть терминал в папке проекта и прописать poetry update . Эта команда установит все библиотеки, требуемые файлом pyproject.toml
Для запуска скрипта нужно просто прописать poetry run python script-name.py
Introduction #
Poetry is a tool for dependency management and packaging in Python. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. Poetry offers a lockfile to ensure repeatable installs, and can build your project for distribution.
System requirements #
Poetry requires Python 3.8+. It is multi-platform and the goal is to make it work equally well on Linux, macOS and Windows.
Installation #
Poetry should always be installed in a dedicated virtual environment to isolate it from the rest of your system. In no case, it should be installed in the environment of the project that is to be managed by Poetry. This ensures that Poetry’s own dependencies will not be accidentally upgraded or uninstalled. (Each of the following installation methods ensures that Poetry is installed into an isolated environment.)
If you are viewing documentation for the development branch, you may wish to install a preview or development version of Poetry. See the advanced installation instructions to use a preview or alternate version of Poetry.
- With pipx
- With the official installer
- Manually (advanced)
- CI recommendations
pipx is used to install Python CLI applications globally while still isolating them in virtual environments. pipx will manage upgrades and uninstalls when used to install Poetry.
pipx install poetry
pipx install
pipx can also install versions of Poetry in parallel, which allows for easy testing of alternate or prerelease versions. Each version is given a unique, user-specified suffix, which will be used to create a unique binary name:
pipx install --suffix
pipx install --suffix
Finally, pipx can install any valid pip requirement spec, which allows for installations of the development version from git , or even for local testing of pull requests:
pipx install --suffix @master git+https://github.com/python-poetry/poetry.git@master pipx install --suffix @pr1234 git+https://github.com/python-poetry/poetry.git@refs/pull/1234/head
pipx upgrade poetry
pipx uninstall poetry
We provide a custom installer that will install Poetry in a new virtual environment and allows Poetry to manage its own environment.
-
Install Poetry The installer script is available directly at install.python-poetry.org, and is developed in its own repository. The script can be executed directly (i.e. ‘curl python’) or downloaded and then executed from disk (e.g. in a CI environment).
The install-poetry.py installer has been deprecated and removed from the Poetry repository. Please migrate from the in-tree version to the standalone version described above.
Linux, macOS, Windows (WSL)
curl -sSL https://install.python-poetry.org
Note: On some systems, python may still refer to Python 2 instead of Python 3. We always suggest the python3 binary to avoid ambiguity.
Windows (Powershell)
If you have installed Python through the Microsoft Store, replace py with python in the command above.
- ~/Library/Application Support/pypoetry on MacOS.
- ~/.local/share/pypoetry on Linux/Unix.
- %APPDATA%\pypoetry on Windows.
If you wish to change this, you may define the $POETRY_HOME environment variable:
curl -sSL https://install.python-poetry.org
If you want to install prerelease versions, you can do so by passing the --preview option to the installation script or by using the $POETRY_PREVIEW environment variable:
curl -sSL https://install.python-poetry.org
Similarly, if you want to install a specific version, you can use --version option or the $POETRY_VERSION environment variable:
curl -sSL https://install.python-poetry.org
You can also install Poetry from a git repository by using the --git option:
curl -sSL https://install.python-poetry.org
- $HOME/.local/bin on Unix.
- %APPDATA%\Python\Scripts on Windows.
- $POETRY_HOME/bin if $POETRY_HOME is set.
If this directory is not present in your $PATH , you can add it in order to invoke Poetry as poetry .
Alternatively, the full path to the poetry binary can always be used:
- ~/Library/Application Support/pypoetry/venv/bin/poetry on MacOS.
- ~/.local/share/pypoetry/venv/bin/poetry on Linux/Unix.
- %APPDATA%\pypoetry\venv\Scripts\poetry on Windows.
- $POETRY_HOME/venv/bin/poetry if $POETRY_HOME is set.
poetry --version
Especially on Windows, self update may be problematic so that a re-install with the installer should be preferred.
poetry self update
If you want to install pre-release versions, you can use the --preview option.
poetry self update --preview
And finally, if you want to install a specific version, you can pass it as an argument to self update .
poetry self update 1.2.0
Poetry 1.1 series releases are not able to update in-place to 1.2 or newer series releases. To migrate to newer releases, uninstall using your original install method, and then reinstall using the methods above.
curl -sSL https://install.python-poetry.org
If you installed using the deprecated get-poetry.py script, you should remove the path it uses manually, e.g.
rm -rf
Also remove ~/.poetry/bin from your $PATH in your shell configuration, if it is present.
Poetry can be installed manually using pip and the venv module. By doing so you will essentially perform the steps carried out by the official installer. As this is an advanced installation method, these instructions are Unix-only and omit specific examples such as installing from git .
The variable $VENV_PATH will be used to indicate the path at which the virtual environment was created.
python3 -m venv
Poetry will be available at $VENV_PATH/bin/poetry and can be invoked directly or symlinked elsewhere.
To uninstall Poetry, simply delete the entire $VENV_PATH directory.
Unlike development environments, where making use of the latest tools is desirable, in a CI environment reproducibility should be made the priority. Here are some suggestions for installing Poetry in such an environment.
Version pinning
Whatever method you use, it is highly recommended to explicitly control the version of Poetry used, so that you are able to upgrade after performing your own validation. Each install method has a different syntax for setting the version that is used in the following examples.
Using pipx
Just as pipx is a powerful tool for development use, it is equally useful in a CI environment and should be one of your top choices for use of Poetry in CI.
pipx install Using install.python-poetry.org
The official installer script (install.python-poetry.org) offers a streamlined and simplified installation of Poetry, sufficient for developer use or for simple pipelines. However, in a CI environment the other two supported installation methods (pipx and manual) should be seriously considered.
Downloading a copy of the installer script to a place accessible by your CI pipelines (or maintaining a copy of the repository) is strongly suggested, to ensure your pipeline’s stability and to maintain control over what code is executed.
By default, the installer will install to a user-specific directory. In more complex pipelines that may make accessing Poetry difficult (especially in cases like multi-stage container builds). It is highly suggested to make use of $POETRY_HOME when using the official installer in CI, as that way the exact paths can be controlled.
Using pip (aka manually)
For maximum control in your CI environment, installation with pip is fully supported and something you should consider. While this requires more explicit commands and knowledge of Python packaging from you, it in return offers the best debugging experience, and leaves you subject to the fewest external tools.
If you install Poetry via pip , ensure you have Poetry installed into an isolated environment that is not the same as the target environment managed by Poetry. If Poetry and your project are installed into the same environment, Poetry is likely to upgrade or uninstall its own dependencies (causing hard-to-debug and understand errors).
Enable tab completion for Bash, Fish, or Zsh #
poetry supports generating completion scripts for Bash, Fish, and Zsh. See poetry help completions for full details, but the gist is as simple as using one of the following:
Bash #
Auto-loaded (recommended) #
poetry completions bash >> ~/.bash_completion
Lazy-loaded #
poetry completions bash >
poetry completions
Zsh #
poetry completions zsh > ~/.zfunc/_poetry
You must then add the following lines in your ~/.zshrc , if they do not already exist:
Oh My Zsh #
mkdir You must then add poetry to your plugins array in ~/.zshrc :
plugins( poetry . )
prezto #
poetry completions zsh > ~/.zprezto/modules/completion/external/src/_poetry
You may need to restart your shell in order for these changes to take effect.
Footer
Python packaging and dependency management made easy.
Documentation
- Introduction
- Basic usage
- Managing dependencies
- Libraries
- Commands
- Configuration
- Repositories
- Managing environments
- Dependency specification
- Plugins
- The pyproject.toml file
- Contributing to Poetry
- Community
- FAQ
- pre-commit hooks
Other Projects
- poetry-core
- install.python-poetry.org
- Bundle plugin
- Export plugin
Copyright © 2018-2023. All Rights Reserved. Powered by
Как пользоваться poetry на windows, при запуске команды poetry install в папке с pyproject.toml возникает странная ошибка
Раньше при команде poetry install устанавливал окружение непонятно куда, но не в папку в которой нахожусь, теперь случается ошибка как показано выше. Как все это починить?
poetry env list Command C:\Users\evyrf\AppData\Local\pypoetry\Cache\virtualenvs\auth&users-z1B85c9s-py3.10\Scripts\python.exe -W ignore - errored with the following return code 1, and o utput: 'C:\Users\evyrf\AppData\Local\pypoetry\Cache\virtualenvs\auth' is not recognized as an internal or external command, operable program or batch file. The system cannot find the path specified. input was : import sys if hasattr(sys, "real_prefix"): print(sys.real_prefix) elif hasattr(sys, "base_prefix"): print(sys.base_prefix) else: print(sys.prefix)
