Platform Engineering · Lesson 06

Python Setup: Versions, Virtual Environments, pip, and Pinned Requirements

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

What you will learn

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.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: where do your packages go, and will they be the same next time?

Pick where packages are installed, whether versions are pinned, and how the project is run.

intactsystem Python
samea rebuild in 4 months
worksimport

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Python environments grow in four levels: one project in a venv, repeatable requirements, several Python versions, and environments built the same way everywhere.

Basic — One project, one venv

At the basic level each project has its own environment.

  • python3 -m venv .venv, activate, deactivate.
  • python -m pip install, never sudo pip.
  • .venv/ in .gitignore.

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.

Intermediate — Repeatable requirements

At the intermediate level anyone can rebuild your environment.

  • Pinned requirements, committed.
  • Rebuilding from scratch to prove it.
  • Separate development requirements (tests, linters).

Try it: Intermediate

A teammate's environment behaves differently from yours. First step?

Now do it: Diff two pip freeze outputs.

Advanced — Several Pythons, locked dependencies

At the advanced level versions are managed deliberately.

  • pyenv or uv for several Python versions; the version recorded in the project.
  • A lock file generated from a short list of direct dependencies, updated on purpose.
  • Dependency scanning (pip-audit) in CI.

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.

Master — The same everywhere

At the master level development, CI, and production build environments the same way.

  • Containers or reproducible builds from the lock file, with hashes checked.
  • An internal package mirror, and policies on new dependencies.
  • Regular, automated dependency updates with tests.

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.

Go deeper

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.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The rebuild nobody changed.

Timeline

  • Month 1A reporting job is written with requirements.txt listing "pandas" and "pyyaml", no versions. It runs nightly in a container built from that file.
  • Month 5The base image is updated for a security fix and the container is rebuilt. pip installs new major versions; the job fails on a changed default and a removed argument.
  • Month 5Two hours of debugging find no code change; comparing pip freeze from the old and new images finds the cause.

What changed after

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.

Try it yourself, from scratch

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.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Which Python, where, and what the system says when you install into it.

    Read-only

    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

    Options: command -v shows the path that will run; python3 -m pip runs the pip that belongs to that Python; grep -m1 -o prints just the first match.

    Expect: Python 3.x.y, /usr/bin/python3, then externally-managed-environment: pip refused, and installed nothing. (On a system without this protection, no line is printed; use a venv anyway.)

    Clean up: cd ~ && rm -rf ~/labs/py (the last step).

  2. Create and activate a virtual environment, and check which Python is now active.

    Reversible

    python3 -m venv .venv && . .venv/bin/activate
    command -v python
    python -c 'import sys; print("in a venv:", sys.prefix != sys.base_prefix)'

    Options: python3 -m venv .venv creates the environment in .venv; . (source) runs the activate script in your current shell, putting .venv/bin first on PATH.

    Expect: A path ending in /labs/py/.venv/bin/python, and in a venv: True.

    If it fails: "ensurepip is not available … apt install python3.x-venv": install the package it names, delete the half-made .venv, and run the command again.

  3. Install an exact version, see what was installed, use it, and record it.

    Reversible

    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

    Options: -q quiet; name==version pins the exact version; pip freeze lists every installed package as name==version.

    Expect: install exit 0, tabulate==0.9.0, a small table with service and replicas columns, and requirements.txt containing tabulate==0.9.0.

  4. Deactivate, and prove the package lives only in the environment.

    Read-only

    deactivate
    python3 -c 'import tabulate' 2>&1 | tail -1
    .venv/bin/python -c 'import tabulate; print("inside the venv:", tabulate.__version__)'

    Expect: ModuleNotFoundError: No module named 'tabulate' from the system Python, then inside the venv: 0.9.0. Calling .venv/bin/python directly works without activating, which is how scripts and services should do it.

  5. Throw the environment away and rebuild it from requirements.txt.

    Potentially destructive

    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__)'

    Options: -r file installs everything listed in the file.

    Expect: rebuilt: 0.9.0: the same version, because it was pinned.

  6. Clean up.

    Potentially destructive

    cd ~ && rm -rf ~/labs/py
    ls ~/labs

    Expect: No error; py is gone, with its environment.

2. Python: pins.py

This 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

3. What to notice

4. Advanced: every step as one Bash script

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

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Your team maintains 12 Python tools and services, installed in different ways on laptops, CI runners, and servers. Design a consistent Python setup.

Clarifying questions to ask

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?

Rough sizing

Say 12 projects, two Python versions in use, about 150 dependencies across them, and weekly security advisories.

Shape of the answer

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.

Trade-offs to name

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.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Forced into the system PythonHop 2: System PythonBreakspip install fails with externally-managed-environment. A forum answer suggests --break-system-packages.
Unpinned requirementsHop 6: RequirementsBreaksrequirements.txt was written by hand: "requests" and "pyyaml", no versions. It installs whatever is newest on the day.
Unpinned requirementsHop 9: RebuildBreaksFour 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.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Which Python → System Python → Create → Activate → Install pinned → Requirements → Run → Isolation → Rebuild. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

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.

Saved on this device, in this browser.
Next in this series · Lesson 07
Containers and a Local Kubernetes Cluster: Docker or Podman, kind, and kubectl

Containers and Kubernetes are where most later labs run, and both can run entirely on your laptop at no cost. A container engine (Docker or Podman) runs containers; kind ("Kubernetes in Docker") runs a whole Kubernetes cluster…

Go to Lesson 07 →

Or browse the full course from the Lessons index.