Python · Module 7 · Lesson 31 min read

pip & Virtual Environments

pip: Python's package installer

pip downloads libraries from PyPI (the Python Package Index), which has over 500,000 packages, like requests, pandas and flask.

Why virtual environments?

Different projects need different library versions. A virtual environment (venv) is a private folder of packages for one project, so projects never clash.

Everyday workflow

  1. Create: python -m venv .venv
  2. Activate:
    • macOS / Linux: source .venv/bin/activate
    • Windows: .venv\Scripts\activate
  3. Install: pip install requests
  4. Save the list: pip freeze > requirements.txt
  5. Recreate elsewhere: pip install -r requirements.txt
  6. Leave: deactivate

Good habits

  • One venv per project, never install into the system Python.
  • Add .venv/ to .gitignore, but commit requirements.txt.
  • Use python -m pip … to be sure pip matches your Python.

💡 Newer tools like uv and Poetry do the same job faster with extra features.

💻 Terminal commands: run them on a computer.

Example

Terminal
# Create and activate a virtual environment
python -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate

# Install packages
python -m pip install --upgrade pip
pip install requests

# Save and restore dependencies
pip freeze > requirements.txt
pip install -r requirements.txt

# See what's installed / remove a package
pip list
pip uninstall requests

deactivate