202 — Working with the OS and Environment Variables

Intermediate

Use Python's stdlib `os` module to read and write environment variables, inspect the running OS, and build portable file paths — then extend `deploy_check.py` to read DEPLOY_ENV, APP_VERSION, and a configurable base path from the environment so behaviour changes without touching argparse.

Learning Objectives

1
Read environment variables safely with os.getenv() and os.environ.get(), supplying defaults
2
Write and delete environment variables at runtime with os.environ
3
Inspect the running OS with os.uname(), os.getpid(), os.getcwd(), and os.cpu_count()
4
Build portable file paths with os.path.join(), os.path.expanduser(), os.path.dirname(), and os.path.basename()
5
Check path existence and metadata with os.path.exists(), os.path.isfile(), os.path.isdir(), and os.path.getsize()
6
Apply the environment-variable config pattern to make a script behaviour-configurable without argparse changes
7
Extend deploy_check.py to read DEPLOY_ENV, APP_VERSION, and BASE_DIR from the environment
Step 1

Set up the lesson 202 workspace

Create a dedicated directory, activate the virtual environment, and confirm the `os` module is available. `os` is part of the Python standard library — no pip install needed.

Commands to Run

mkdir -p ~/devops-python/lesson-202
cd ~/devops-python/lesson-202
source ~/devops-python/lesson-101/devops-env/bin/activate
python3 -c "import os; print('os module OK'); print('platform:', os.name)"

What This Does

The os module provides a portable interface to operating-system functionality: environment variables, process information, file-system path manipulation, and more. os.name returns 'posix' on Linux and macOS, 'nt' on Windows.

Because it is part of the standard library, import os is all you need — no installation step.

Expected Outcome

Your terminal prompt shows (devops-env).

The one-liner prints os module OK followed by platform: posix (on Linux or macOS).

Pro Tips

  • 1
    If you placed your virtual environment at a different path in Lesson 101, adjust the `source` command to match your actual venv location.
  • 2
    `os.name` is a coarse platform check. For finer-grained detection (distinguishing Linux from macOS), use `import platform; platform.system()` which returns `'Linux'`, `'Darwin'`, or `'Windows'`.
Was this step helpful?

All Steps (0 / 8 completed)