Launching Python Scripts Developed with Poetry

Viewed 955

I've developed plenty of utilities using virtualenv that have gone on to become packages of their own. But poetry is the hot new thing, so I figured I'd give it a go.

Creating a new environment with poetry new was easy, and installing its dependencies with poetry install was also a snap.

But trying to actually launch my script from a directory other than its project directory has proven a challenge. I've added the [tools.poetry.scripts] section to its pyproject.toml file, so I can launch it from within the project directory by calling poetry run [args]. That's not too terrific for getting other people to try my fancy new script, though. And it's a non-starter if you want (or need) to runt from some other directory.

So, what's the secret?

3 Answers

A bit late but answering for anyone searching for this in the future.


Adding an entry to the pyproject.toml's [tools.poetry.scripts] is analogous to setup.py's console_scripts.

So for distributing your code you would want to poetry build and pass the resultant artifact to your users (be it through putting it up on Github in the Release page of your project, by publishing to PyPI, or putting it on a USB and throwing it at them).

Users can then pip install -U as normal (be that pip install -U foobar or pip install -U ./foobar-0.0.0-py3-none-any.whl) and it'll be available to run in the command line.

Though for most end user environment I recommend pipx install instead as it'll create individual virtualenvs for each installed package and provides an easier process to upgrade the collective set of things installed. Be sure to checkout things like shiv or pyinstaller if you want to provide a more "download and run" experience.

The point of this question is that while developing your tool, you may want to run it in another directory without having to build and install it after each edit.

It took me a while of searching to figure this out, but the best method is to call the virtual environment's install point directly.

In linux, the install is probably located here:

~/.cache/pypoetry/virtualenvs/<venv_name>/bin/<tool>

The <venv_name> is the name of the virtual environment, which you can get by running this in your poetry project*:

poetry env list

Or, you can get the full path to this environment with:

poetry env list --full-path

*As of this writing, I am using poetry version 1.1.13

IMO the main goal of poetry run is testing during development.

You should provide a sdist or wheel for other people or tell them to do a pip install /path/to/the/project (pip version >= 19 required) to install your package directly. Than they don't need a poetry run at all.

Related