Building CLI Tools

💤0
Lv 10 XP
← ⚙️ Scripting & Automation · Python

Building CLI Tools

Intermediate ⭐ 80 XP ⏱ 16 min #python#cli#argparse

Turn a script into a proper command-line tool with arguments, flags, and help.

📖Theory

A real CLI tool accepts arguments and flags, validates input, prints help, and returns a meaningful exit code. Python’s built-in argparse handles all of this: positional arguments, optional --flags, defaults, types, and an auto-generated --help.

The conventions that make a tool feel professional: exit 0 on success and non-zero on failure, write errors to stderr, and guard the entry point with if __name__ == "__main__": so the file can also be imported as a module.

🌍Real-World Example
#!/usr/bin/env python3
import argparse, sys

def main():
    p = argparse.ArgumentParser(description="Scale a deployment")
    p.add_argument("name", help="deployment name")
    p.add_argument("-r", "--replicas", type=int, default=1)
    p.add_argument("--dry-run", action="store_true")
    args = p.parse_args()

    if args.replicas < 0:
        print("replicas must be >= 0", file=sys.stderr)
        return 1
    action = "Would scale" if args.dry_run else "Scaling"
    print(f"{action} {args.name} to {args.replicas} replicas")
    return 0

if __name__ == "__main__":
    sys.exit(main())
✍️Hands-On Exercise
  1. Build a CLI with one positional argument and one optional --count flag.
  2. Add a --verbose boolean flag using action="store_true".
  3. Make the tool return exit code 1 on invalid input and test with echo $?.
  4. Run it with --help and read the auto-generated usage.
🧾Cheat Sheet
TaskCode
Parserargparse.ArgumentParser()
Positional argadd_argument("name")
Optional flagadd_argument("--count", type=int)
Boolean flagaction="store_true"
Defaultdefault=…
Parseargs = p.parse_args()
Exit codesys.exit(0)
💬Common Interview Questions
What does argparse give you over reading sys.argv directly?

Declarative arguments with types, defaults, validation, required/optional flags, and an auto-generated —help and usage message — far less error-prone manual parsing.

Why does CLI exit code matter?

Other programs and CI pipelines branch on it: 0 means success, non-zero means failure. A tool that always exits 0 can’t be reliably scripted.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type