Your operating system already has a Python, and it belongs to the operating system: system tools depend on the exact packages it has. So every project gets its own virtual environment, a private folder with its own Python and its own packages, created with python3 -m venv. Packages are installed into it with pip at pinned versions, and recorded in requirements.txt so anyone can rebuild exactly the same environment. This lesson follows one project from "which Python do I have?" to a rebuilt environment, and shows two failures: forcing packages into the system Python, and installing without pinning versions.
Difficulty: Beginner · Know this first: Lesson 03
By the end of this lesson you can work at four levels:
This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.
This bar adds up minutes from needing a library to having an environment anyone can rebuild. It is a worked example, not a measurement. The system Python and requirements hops decide whether the setup is safe and whether it stays the same.
Pick where packages are installed, whether versions are pinned, and how the project is run.
Three questions. No score is saved anywhere — this is just you against the material.
Python environments grow in four levels: one project in a venv, repeatable requirements, several Python versions, and environments built the same way everywhere.
At the basic level each project has its own environment.
Where it breaks: forgetting to activate, and installing into the wrong Python.
Try it: Basic
How do you know which Python and pip are active?
Now do it: Run it with and without the venv active.
At the intermediate level anyone can rebuild your environment.
Try it: Intermediate
A teammate's environment behaves differently from yours. First step?
Now do it: Diff two pip freeze outputs.
At the advanced level versions are managed deliberately.
Try it: Advanced
Why keep a short list of direct dependencies and generate the pinned file from it?
Now do it: Try pip-tools or uv on a small project.
At the master level development, CI, and production build environments the same way.
Trade-off: strict pins never change by surprise, and never pick up security fixes by themselves either; automate updates so pinning does not become standing still.
Try it: Master
Pinned dependencies have a known vulnerability. What do you do?
Now do it: Run pip-audit on a project.
A project layout and the commands that go with it:
project/ .gitignore # contains .venv/ requirements.txt # pinned: tabulate==0.9.0 report.py python3 -m venv .venv # once per machine (or after a Python upgrade) .venv/bin/python -m pip install -r requirements.txt .venv/bin/python report.py # no activation needed in scripts and services
pip-tools: write requirements.in with your direct dependencies (tabulate), run pip-compile to produce a fully pinned requirements.txt, and pip-sync to make the environment match it exactly. uv offers the same with uv pip compile and uv pip sync, much faster, and can install Python versions too.
pipx installs command-line tools written in Python (such as pipx install httpie) each in its own environment, with the command available on your PATH: the right answer to "I want this tool everywhere" on a system whose Python is externally managed.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. The rebuild nobody changed.
Dependencies are compiled into a pinned lock file, the container is built from it, a dependency bot opens update pull requests weekly with tests, and the old image's pip freeze is kept with each release.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: Python 3.10 or newer and the venv module (sudo apt install -y python3-venv on Debian or Ubuntu; included with Homebrew's Python on macOS), and internet access to PyPI for one small package.
Type each one, read what it prints, and compare it with the note above it.
Which Python, where, and what the system says when you install into it.
mkdir -p ~/labs/py && cd ~/labs/py python3 --version; command -v python3 python3 -m pip install tabulate 2>&1 | grep -m1 -o externally-managed-environment
Create and activate a virtual environment, and check which Python is now active.
python3 -m venv .venv && . .venv/bin/activate
command -v python
python -c 'import sys; print("in a venv:", sys.prefix != sys.base_prefix)'Install an exact version, see what was installed, use it, and record it.
python -m pip install -q "tabulate==0.9.0"; echo "install exit $?" python -m pip freeze python -c 'from tabulate import tabulate; print(tabulate([["web", 3], ["db", 1]], headers=["service", "replicas"]))' python -m pip freeze > requirements.txt && cat requirements.txt
Deactivate, and prove the package lives only in the environment.
deactivate
python3 -c 'import tabulate' 2>&1 | tail -1
.venv/bin/python -c 'import tabulate; print("inside the venv:", tabulate.__version__)'Throw the environment away and rebuild it from requirements.txt.
rm -rf .venv && python3 -m venv .venv
.venv/bin/python -m pip install -q -r requirements.txt
.venv/bin/python -c 'import tabulate; print("rebuilt:", tabulate.__version__)'Clean up.
cd ~ && rm -rf ~/labs/py ls ~/labs
pins.pyThis program reads a requirements file the way a reviewer or a CI check would: it separates pinned requirements (name==version) from loose ones, flags loose ones as the cause of drift, and compares two pip freeze outputs to show exactly what changed between an old and a new environment. Save it as pins.py, then run it.
# pins.py
import re
REQUIREMENTS = """
tabulate==0.9.0
requests>=2.28
pyyaml
# a comment
urllib3==2.2.3
"""
LINE = re.compile(r"^([A-Za-z0-9_.-]+)\s*(==|>=|<=|~=|>|<)?\s*([0-9][^\s;#]*)?")
pinned, loose = [], []
for raw in REQUIREMENTS.strip().splitlines():
raw = raw.strip()
if not raw or raw.startswith("#"):
continue
name, op, ver = LINE.match(raw).groups()
(pinned if op == "==" else loose).append((name.lower(), op or "", ver or ""))
for n, op, v in pinned:
print(f"pinned {n}=={v}")
for n, op, v in loose:
print(f"LOOSE {n}{op}{v} any {'newer ' if op else ''}version can arrive on the next rebuild")
print()
OLD = {"requests": "2.31.0", "pyyaml": "6.0.1", "urllib3": "2.2.3", "tabulate": "0.9.0"}
NEW = {"requests": "2.32.3", "pyyaml": "7.0.0", "urllib3": "2.2.3", "tabulate": "0.9.0", "packaging": "25.0"}
for name in sorted(set(OLD) | set(NEW)):
a, b = OLD.get(name), NEW.get(name)
if a == b:
continue
if a is None:
print(f"added {name} {b}")
elif b is None:
print(f"removed {name} {a}")
else:
major = a.split(".")[0] != b.split(".")[0]
print(f"changed {name} {a} -> {b}{' MAJOR: expect breaking changes' if major else ''}")
Run it, and you should see this output:
$ python3 pins.py pinned tabulate==0.9.0 pinned urllib3==2.2.3 LOOSE requests>=2.28 any newer version can arrive on the next rebuild LOOSE pyyaml any version can arrive on the next rebuild added packaging 25.0 changed pyyaml 6.0.1 -> 7.0.0 MAJOR: expect breaking changes changed requests 2.31.0 -> 2.32.3
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/python-setup-versions-virtual-environments-and-pip && cd ~/labs/python-setup-versions-virtual-environments-and-pip) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Python Setup: Versions, Virtual Environments, pip, and Pinned Requirements", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Which Python, where, and what the system says when you install into it.'
'Create and activate a virtual environment, and check which Python is now active.'
'Install an exact version, see what was installed, use it, and record it.'
'Deactivate, and prove the package lives only in the environment.'
'Throw the environment away and rebuild it from requirements.txt.'
'Clean up.'
)
step_1() {
mkdir -p ~/labs/py && cd ~/labs/py
python3 --version; command -v python3
python3 -m pip install tabulate 2>&1 | grep -m1 -o externally-managed-environment
}
step_2() {
python3 -m venv .venv && . .venv/bin/activate
command -v python
python -c 'import sys; print("in a venv:", sys.prefix != sys.base_prefix)'
}
step_3() {
python -m pip install -q "tabulate==0.9.0"; echo "install exit $?"
python -m pip freeze
python -c 'from tabulate import tabulate; print(tabulate([["web", 3], ["db", 1]], headers=["service", "replicas"]))'
python -m pip freeze > requirements.txt && cat requirements.txt
}
step_4() {
deactivate
python3 -c 'import tabulate' 2>&1 | tail -1
.venv/bin/python -c 'import tabulate; print("inside the venv:", tabulate.__version__)'
}
step_5() {
rm -rf .venv && python3 -m venv .venv
.venv/bin/python -m pip install -q -r requirements.txt
.venv/bin/python -c 'import tabulate; print("rebuilt:", tabulate.__version__)'
}
step_6() {
cd ~ && rm -rf ~/labs/py
ls ~/labs
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
grep, tail, mkdir, rm, cat, echo, ls, cd, Pipes, Redirection, If...Else, Exit codes.Your team maintains 12 Python tools and services, installed in different ways on laptops, CI runners, and servers. Design a consistent Python setup.
Which Python versions are used, and how are they installed? Where do packages go on laptops, in CI, and on servers? How are dependencies declared, pinned, and updated? How are command-line tools installed? How do you check an environment matches what was tested?
Say 12 projects, two Python versions in use, about 150 dependencies across them, and weekly security advisories.
One Python version per project recorded in the repository; uv or pyenv to install it; a venv per project; direct dependencies in one file and a pinned lock file generated from it; CI that rebuilds from the lock file and runs pip-audit; services built into containers from the lock file; pipx for command-line tools; a dependency bot with tests for updates.
Lock files add a step to every dependency change and remove "it worked yesterday" surprises; containers make servers match CI at the cost of image builds.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Forced into the system Python | Hop 2: System Python | Breaks | pip install fails with externally-managed-environment. A forum answer suggests --break-system-packages. |
| Unpinned requirements | Hop 6: Requirements | Breaks | requirements.txt was written by hand: "requests" and "pyyaml", no versions. It installs whatever is newest on the day. |
| Unpinned requirements | Hop 9: Rebuild | Breaks | Four months later CI rebuilds from requirements.txt and gets new major versions of both libraries. A changed default makes the YAML loader reject a file, and a removed function breaks an import. Two hours to find that the code did not change. |
The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.
Last updated . Next review due by November 2027. Found something out of date? Tell me.