Installing a package with pip (from the earlier Modules and Imports lesson) normally installs it globally — shared across every Python project on the machine. A virtual environment gives one project its own isolated set of installed packages instead.
Project A needs version 1 of a library; Project B needs version 2 — installed globally, only one can be satisfied at a time. A virtual environment per project makes this a non-issue.
venv is built into Python — no separate install needed.
python -m venv venv
# Creates a "venv" folder holding an isolated Python installation# macOS / Linux
source venv/bin/activate
# Windows
venv\Scripts\activate
# The terminal prompt changes to show it's active, e.g.:
(venv) $Once active, pip install only affects this environment — not the system-wide Python or any other project's environment.
(venv) $ pip install requests
# Installed only inside this project's venv folder(venv) $ deactivateA requirements.txt file lists exactly what a project needs, so a teammate — or a deployment server — can recreate the same environment.
# Save the current environment's packages to a file
pip freeze > requirements.txt
# On another machine, recreate it
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt| Command | What it does |
|---|---|
| python -m venv venv | Creates a new virtual environment |
| source venv/bin/activate (or venv\Scripts\activate on Windows) | Activates it for the current terminal session |
| deactivate | Returns to the system-wide Python |
| pip freeze > requirements.txt | Records exactly what's installed |
| pip install -r requirements.txt | Reinstalls everything a requirements.txt lists |
What not to commit
The venv folder itself should never be committed to version control — it's regenerated from requirements.txt on any machine. Add it to .gitignore from the start of a project.