Poetry Commands - Python Dependency Management

Master Poetry commands for Python dependency management. Learn to install, update, add, remove, build, and publish packages with this comprehensive guide.

Poetry Commands Guide

Poetry is a powerful tool for dependency management and packaging in Python. This guide provides a quick reference for essential Poetry commands to streamline your Python development workflow.

Poetry Project Initialization and Setup

Start new Python projects or initialize Poetry in existing ones with these commands.

  • poetry new my-package: Creates a new Python package structure.
  • poetry init: Initializes Poetry in an existing project, creating a pyproject.toml file.
  • poetry lock --no-update: Regenerates the poetry.lock file without updating existing dependencies.

Managing Dependencies with Poetry

Effectively manage your project's dependencies using Poetry's add, remove, and update functionalities.

  • poetry install: Installs all dependencies specified in poetry.lock.
  • poetry install --no-dev: Installs only production dependencies.
  • poetry install --remove-untracked: Installs dependencies and removes old ones not present in the lock file.
  • poetry update: Updates all dependencies to their latest compatible versions.
  • poetry update <package> ...: Updates specific package(s).
  • poetry add <package>: Adds a new dependency to the project.
  • poetry add -D flake8 black isort pytest pytest-cov mypy types-requests: Adds development dependencies.
  • poetry add git+https://github.com/sdispater/pendulum.git#develop: Adds a dependency from a Git repository (HTTPS).
  • poetry add git+ssh://git@github.com/sdispater/pendulum.git#2.0.5: Adds a dependency from a Git repository (SSH).
  • poetry add ./my-package/ ../my-package-2/: Adds local path dependencies.
  • poetry add "<package>[<extra>]": Adds a package with specific extras.
  • poetry remove <package>: Removes a package from the project.

Working with Poetry Projects

Build, publish, and run your Python projects using Poetry.

  • Editable mode: Define dependencies in pyproject.toml like my-package = {path = "../my/path", develop = true} for development.
  • poetry show: Displays all installed packages and their versions.
  • poetry build: Builds the project into source and wheel distributions.
  • poetry publish: Publishes the package to a repository (e.g., PyPI).
  • poetry run python -v: Executes a command within the project's virtual environment.
  • Scripts: Define custom scripts in pyproject.toml under [tool.poetry.scripts], e.g., my-script = "my_module:main", and run them with poetry run my-script.
  • poetry shell: Activates the project's virtual environment in a new shell.

Poetry simplifies Python development by providing a unified interface for dependency management, packaging, and publishing. Refer to the official Poetry documentation for more advanced usage and configuration options.