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
- Managing Dependencies
- Virtual Environment
- Running Code
- Scripts
- Configuration
- Additional Resources
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.
- Adding a dependency:
poetry add <library>
- Removing a dependency:
poetry remove <library>
- Updating a dependency:
poetry update <library>
- Listing dependencies:
poetry show
- 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 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.
Poetry allows you to define custom scripts within your pyproject.toml file. This is useful for encapsulating frequently used commands or automating tasks.
- Define the script in pyproject.toml:
[tool.poetry.scripts]
test = 'scripts:test'
- 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']
)
- Run the script:
poetry run test
- 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.
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.