Homepage

Project configuration

New project

$ poetry new my-app

Existing project

$ cd my-app
$ poetry init

Package mode

Disable package mode, useful for if you intend to run directly and not as an installed package.

[tool.poetry]
package-mode = false

Otherwise you have to add this flag in the CLI:

$ poetry install --no-root

Dependencies

List dependencies

$ poetry show

Add dependency

$ poetry add PACKAGE
$ poetry add PACKAGE==VERSION

Dev package:

$ poetry add -D PACKAGE
$ poetry add --dev PACKAGE
$ poetry add -G dev PACKAGE

For extras, make sure to quote the hard brackets:

$ poetry add 'lxml[html-clean]'

Result:

lxml = { extras = ["html-clean"], version = "^5.3.0" }

Prod vs dev dependencies

[tool.poetry.dependencies]
python = "..."
abc = "..."

[tool.poetry.group.dev.dependencies]
def = "..."

Lock dependencies

Lock minor version

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

Lock patch version

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

Lock a range

[tool.poetry.dependencies]
python = ">=3.10,<3.13"

Virtual environments

Location

Default location

By default, Poetry creates an environment here in a central locatiion:

  • {cache-dir}/virtualenvs

That uses the Cache directory.

  • macOS - ~/Library/Application Support/pypoetry
  • Windows - C:\Users\<username>\AppData\Roaming\pypoetry

In project

You can choose to create a virtual environment in the project. This makes it easier for configuring your IDE to recognize it for new terminal sessions and loading dependencies when viewing Python files.

  • poetry.toml (not pyproject.toml)
      [virtualenvs]
      in-project = true
    

Activate environment

This creates a subshell, so when you exit the subshell no changes are persisted.

$ $(poetry env activate)

Note the command alone only prints, so you need to add the outside level to execute.

The old way for Poetry v1 was poetry shell and now you need a plugin for that for v2.

Or, if you made the virtual env in your project.

$ source {path_to_venv}/bin/activate
> source {path_to_venv}\Scripts\activate.bat

And deactivate with:

$ deactivate

Get path to virtual env

$ poetry env info --path

Run commands in the environment

Interactive console:

$ poetry run python

Run a script:

$ poetry run python your_script.py

Run a CLI tool from the installed packages:

$ poetry run pytest