Guide to Working with Pip and Poetry
Overview
Pip and Poetry are both tools used for managing Python packages and virtual environments. Pip is the standard package manager for Python, while Poetry is a modern alternative that simplifies dependency management and project packaging.
When to Use What?
- Use Pip if you want a simple way to install packages and manage dependencies manually.
- Use Poetry if you want an all-in-one solution for dependency management, virtual environments, and project packaging.
Working with Pip
1. Installing Pip
Most Python installations come with Pip pre-installed. To check if you have Pip:
pip --version
If not installed, install it with:
python -m ensurepip --default-pip
2. Setting Up a Virtual Environment
Creating a virtual environment ensures that dependencies remain isolated from system-wide Python packages.
Create a Virtual Environment
python -m venv myenv
Activate the Virtual Environment
- Windows:
myenv\Scripts\activate
- Mac/Linux:
source myenv/bin/activate
3. Loading the Virtual Environment in VS Code
- Open VS Code.
- Press
Ctrl + Shift + P
and type Python: Select Interpreter. - Choose the Python interpreter from your virtual environment.
4. Adding and Removing Packages
Install a Package
pip install package_name
Uninstall a Package
pip uninstall package_name
Save Installed Packages to a File
pip freeze > requirements.txt
Install Packages from a Requirements File
pip install -r requirements.txt
Working with Poetry
1. Installing Poetry
Poetry can be installed using:
curl -sSL https://install.python-poetry.org | python3 -
Verify installation:
poetry --version
2. Setting Up a Virtual Environment
Create a New Project
poetry new myproject
cd myproject
Initialize Poetry in an Existing Project
poetry init
Activate the Virtual Environment
poetry shell
3. Loading the Virtual Environment in VS Code
- Open VS Code.
- Press
Ctrl + Shift + P
and type Python: Select Interpreter. - Select the Poetry environment interpreter.
4. Adding and Removing Packages
Install a Package
poetry add package_name
Remove a Package
poetry remove package_name
pyproject.toml
Install Dependencies from poetry install
Summary
- Pip is simpler and best for quick setups or small projects.
- Poetry is more structured and useful for managing dependencies in larger projects.
- Both tools help create virtual environments and manage dependencies efficiently.
Choose based on your project needs!