Poetry is a dependency manager for Python that makes it easy to manage project dependencies and create self-contained virtual environments. To use Poetry to install packages in a Python project, follow these steps:
Install Poetry:
First, you need to install Poetry on your system. You can do this by running the following command (you may need administrative privileges):
Create a new project or navigate to an existing one:
If you're starting a new project, create a new directory for it and navigate to that directory in your terminal. If you already have an existing project, navigate to the project's root directory.
Initialize Poetry:
Run the following command to initialize a new Poetry project and create a pyproject.toml file:
code
poetry init
Follow the prompts to set up your project's dependencies and requirements.
Add a package:
To install a new package, use the poetry add command followed by the package name. For example, to install the requests package:
code
poetry add requests
This command will add the package to your pyproject.toml file and install it in the project's virtual environment.
Update an existing package:
If you want to update a package to its latest version, use the poetry update command followed by the package name (optional):
code
poetry update requests
If you don't specify a package name, it will update all the packages in your project.
Lock dependencies:
To create a poetry.lock file, which ensures that the exact versions of dependencies are used across different environments, run:
code
poetry lock
Activate the virtual environment:
To work with the installed packages in the project, activate the virtual environment:
Linux/macOS:
code
poetry shell
Windows:
code
.venv\Scripts\activate
Now you're inside the virtual environment, and you can run your Python scripts or import the installed packages.
Exit the virtual environment:
When you're done, exit the virtual environment by typing exit in the terminal.
Remember that Poetry manages the dependencies locally for each project, so you don't need to worry about conflicts between projects.