pip & Virtual Environments

Install third-party packages and isolate project dependencies.

Syntaxpython -m venv .venv pip install requests

Beyond 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

Example · python
# 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 environment

When 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.

Example · bash
# Create venv
python3 -m venv .venv

# Activate (macOS / Linux)
source .venv/bin/activate

# Activate (Windows)
# .venv\Scripts\activate

python --version   # uses the venv's Python

Install packages with pip

Installs two packages and a version-pinned Flask, then lists all installed packages.

Example · bash
pip install requests beautifulsoup4
pip install 'flask>=3.0,<4'
pip list   # show installed packages

Freeze and restore dependencies

Captures exact package versions in requirements.txt for reproducible installs elsewhere.

Example · bash
# 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

  • Be the first to comment on this lesson.