Unit 12 — Virtual Environments and Packages — Isolating Your Dependencies
Why Virtual Environments?
When you install a package with pip install requests, it goes into your system Python. If two projects need different versions of the same package, they conflict. A virtual environment is an isolated Python installation for one project — it has its own packages, its own pip, and leaves your system Python untouched.
Every real Python project uses one. In network automation, this matters: netmiko 4.x and 3.x have breaking API changes. Without a venv, updating one project breaks another.
Creating and Activating a venv
python3 -m venv venv
This creates a venv/ directory in your project folder. Activate it:
source venv/bin/activate # Linux / macOS
venv\Scripts\activate # Windows
Your prompt changes to show (venv) — any python3 or pip command now uses the isolated environment.
Deactivate when done:
deactivate
Installing Packages
With the venv active, install packages normally:
pip install requests
pip install requests==2.31.0 # pin a specific version
pip install "requests>=2.28" # minimum version constraint
List installed packages:
pip list
Show details about one package:
pip show requests
requirements.txt — Sharing Your Dependencies
requirements.txt lists all the packages your project needs so others (or the Pi) can install the same set with one command.
Freeze your current environment to generate the file:
pip freeze > requirements.txt
This writes every installed package and its exact version, for example:
certifi==2024.2.2
charset-normalizer==3.3.2
idna==3.6
requests==2.31.0
urllib3==2.2.1
Install from a requirements file on another machine or after cloning:
pip install -r requirements.txt
What Goes in .gitignore
The venv/ directory contains thousands of files — never commit it. Add it to .gitignore:
venv/
__pycache__/
*.pyc
.env
Commit requirements.txt instead. Anyone who clones the repo runs pip install -r requirements.txt to recreate the environment.
Checking Which Python You Are Using
which python3 # /home/emmy/myproject/venv/bin/python3
python3 --version # Python 3.11.x
pip --version # pip 24.x from .../venv/lib/...
If the path shows venv/bin/, the venv is active. If it shows /usr/bin/, you are in the system Python.
Summary
python3 -m venv venvcreates an isolated environment invenv/source venv/bin/activateactivates it — your prompt shows(venv)pip install <package>installs only into the active venvpip freeze > requirements.txtcaptures all installed versionspip install -r requirements.txtrecreates the environment elsewhere- Never commit
venv/— commitrequirements.txtinstead