pip & Virtual Environments
Install third-party packages and isolate project dependencies.
Syntax
python -m venv .venv
pip install requestsBeyond the standard library, hundreds of thousands of packages live on PyPI (the Python Package Index). You install them with pip.
Virtual environments
A virtual environment is an isolated set of packages for one project, so different projects do not interfere with each other. Create one with the venv module, then activate it before installing packages.
Example
# Run these in your terminal:
#
# python -m venv .venv
# source .venv/bin/activate (Windows: .venv\Scripts\activate)
# pip install requests
# pip freeze > requirements.txt
#
# Then in your Python file:
import requests # now available inside the environmentWhen to use it
- A developer creates a virtual environment per project so conflicting library versions never clash.
- A CI pipeline installs dependencies from requirements.txt into a fresh venv before running tests.
- A data scientist installs pandas and matplotlib with pip into an isolated environment for analysis.
More examples
Create and activate a virtual environment
Creates an isolated .venv directory and activates it so subsequent pip installs go there.
# Create venv
python3 -m venv .venv
# Activate (macOS / Linux)
source .venv/bin/activate
# Activate (Windows)
# .venv\Scripts\activate
python --version # uses the venv's PythonInstall packages with pip
Installs two packages and a version-pinned Flask, then lists all installed packages.
pip install requests beautifulsoup4
pip install 'flask>=3.0,<4'
pip list # show installed packagesFreeze and restore dependencies
Captures exact package versions in requirements.txt for reproducible installs elsewhere.
# Save current environment to a file:
pip freeze > requirements.txt
# Restore on another machine:
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
Discussion