103 — Building CLI Tools with argparse

Intermediate

Replace manual sys.argv handling with Python's built-in argparse module to define named arguments, optional flags, restricted choices, and auto-generated --help output — the pattern behind every professional Python CLI tool.

Learning Objectives

1
Create an ArgumentParser and replace sys.argv with parse_args()
2
Define a required positional argument using add_argument()
3
Add optional flags with -- prefixes and default values
4
Restrict argument values to a known set with choices=
5
Let argparse auto-generate --help output and handle missing-argument errors
6
Use parsed argument values to control script behaviour
Step 1

Set up the lesson 103 workspace

Create a directory for this lesson, activate the shared virtual environment, and copy `deploy_check.py` from Lesson 102 as the starting point. Lesson 103 evolves that script from raw sys.argv to a fully-specified argparse CLI.

Commands to Run

mkdir -p ~/devops-python/lesson-103
cd ~/devops-python/lesson-103
cp ~/devops-python/lesson-102/deploy_check.py .
source ~/devops-python/lesson-101/devops-env/bin/activate
cat deploy_check.py

What This Does

Copying deploy_check.py from Lesson 102 gives you the shebang, chmod +x history, and the sys.argv guard that you will now replace.

The argparse module is part of the Python standard library — no pip install needed, just import argparse.

Expected Outcome

Your terminal prompt shows (devops-env). cat deploy_check.py shows the 8-step version from Lesson 102: shebang on line 1, len(sys.argv) < 2 guard, environment = sys.argv[1], and the status header print block.

Pro Tips

  • 1
    If you did not complete Lesson 102, create `deploy_check.py` with any content — you will rewrite it completely in this lesson.
  • 2
    The `source` path assumes the venv is at `~/devops-python/lesson-101/devops-env/`. Adjust if you placed it elsewhere.
Was this step helpful?

All Steps (0 / 8 completed)