Skip to content

Instantly share code, notes, and snippets.

@kuldeepluvani
Last active May 2, 2024 20:35
Show Gist options
  • Save kuldeepluvani/6621b700da1c05580c5efc34b606f909 to your computer and use it in GitHub Desktop.
Save kuldeepluvani/6621b700da1c05580c5efc34b606f909 to your computer and use it in GitHub Desktop.
Poetry Cheatsheet: Basic

Poetry Cheatsheet: Basics

This gist provides a quick reference for essential Poetry commands, helping you manage Python dependencies and packaging with ease.

Table of Contents

Creating a Project

poetry new <project-name>

This command generates a new project directory with the necessary structure and files for your Python project, including a pyproject.toml configuration file.

Managing Dependencies

  • Adding a dependency:
poetry add <library>
  • Removing a dependency:
poetry remove <library>
  • Updating a dependency:
poetry update <library>
  • Listing dependencies:
poetry show

Virtual Environment

  • Get virtual environment path:
poetry env info --path
  • Disable virtual environment creation:
poetry config virtualenvs.create false

This can be useful if you prefer to manage virtual environments manually or with other tools.

Running Code

  • Running your application:
poetry run python app.py

The poetry run command ensures that your code is executed within the context of the project's virtual environment.

  • Running tests:
poetry run python -m unittest discover

This command will discover and run all unit tests within your project.

Scripts

Poetry allows you to define custom scripts within your pyproject.toml file. This is useful for encapsulating frequently used commands or automating tasks.

  1. Define the script in pyproject.toml:
[tool.poetry.scripts]
test = 'scripts:test'
  1. Create a scripts.py file:
import subprocess

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

Configuration

  • List configuration options:
poetry config --list
  • Set a configuration option:
poetry config virtualenvs.in-project true
  • Open new shell instance with activated environment:
poetry shell

This command enables the creation of the virtual environment within the project directory.

Additional Resources

Please note that this cheatsheet is not exhaustive and only covers some of the most commonly used Poetry commands. Refer to the official documentation for more comprehensive information and advanced usage.

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