Building CLI Tools
Turn a script into a proper command-line tool with arguments, flags, and help.
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.
#!/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()) - Build a CLI with one positional argument and one optional
--countflag. - Add a
--verboseboolean flag usingaction="store_true". - Make the tool return exit code 1 on invalid input and test with
echo $?. - Run it with
--helpand read the auto-generated usage.
Cheat Sheet▾
| Task | Code |
|---|---|
| Parser | argparse.ArgumentParser() |
| Positional arg | add_argument("name") |
| Optional flag | add_argument("--count", type=int) |
| Boolean flag | action="store_true" |
| Default | default=… |
| Parse | args = p.parse_args() |
| Exit code | sys.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.