Skip to content

Instantly share code, notes, and snippets.

Last active July 12, 2024 17:05
Show Gist options
  • Save CarlosDomingues/b88df15749af23a463148bd2c2b9b3fb to your computer and use it in GitHub Desktop.
Save CarlosDomingues/b88df15749af23a463148bd2c2b9b3fb to your computer and use it in GitHub Desktop.
Python Poetry Cheatsheet

Create a new project

poetry new <project-name>

Add a new lib

poetry add <library>

Remove a lib

poetry remove <library>

Update a lib

poetry update <library>

Get venv path

poetry run which python

Run app

poetry run python

Run tests

poetry run python -m unittest discover

Show dependencies

poetry show

Create script

1 - Edit pyproject.toml:

test = 'scripts:test'

2 - Create a file on the root directory of your project:

import subprocess

def test():
    Run all unittests. Equivalent to:
    `poetry run python -u -m unittest discover`
        ['python', '-u', '-m', 'unittest', 'discover']

3 - Run script:

poetry run test

Disable virtual environment creation

poetry config virtualenvs.create false

List configuratiom

poetry config --list
Copy link

I just couldn't make this to work:

test = 'scripts:test'

Have you ? The official doc is not verbose about it.

For the test() command, I've found useful to replace with a function like this:

def run(command: list[str]):
    """Run the command transparently (as if it was in the same process).

    If an error occurs, exit with the corresponding return code.
    Prints all outputs to stdout.
    result =, capture_output=True)
    print(result.stdout.decode('utf8'), end='')
    print(result.stderr.decode('utf8'), end='')
    if result.returncode != 0:

As unittest seems to return even non error outputs into stderr. Also, capturing the result make it possible for you to return a non zero exit code, which is useful in CI pipeline.

Copy link

rmmajor commented Dec 4, 2022

There is a typo in 'Add a new lib' section: not potry but poetry. Hope this helps

Copy link

Thanks @rmmajor, I've fixed it.

A disclaimer, though: I don't use poetry anymore, so I'm not sure how up to date this cheat sheet is =/

Copy link

++ poetry shell to activate virtual environment
++ poetry install to install dependencies from poetry files

@CarlosDomingues interesting comment, what package / dependency tool are you now using ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment