Interview Prep/Python for DevOps/OS, filesystem, subprocess & CLIs

How do you parse command-line arguments with `argparse`?

BeginnerConceptOS, filesystem, subprocess & CLIs
Answer
import argparse
p = argparse.ArgumentParser(description="Stop idle dev instances")
p.add_argument("--region", default=os.getenv("AWS_REGION", "us-east-1"))
p.add_argument("--tag", action="append", default=[], help="key=value, repeatable")
p.add_argument("--days", type=int, default=7)
p.add_argument("--dry-run", action="store_true")
p.add_argument("-v", "--verbose", action="count", default=0)
args = p.parse_args()

argparse generates --help, validates types, and exits with code 2 and a usage message on bad input. It is in the standard library, so scripts that must run on a bare host prefer it.

All Python for DevOps questions Roadmap: Python for automation

More on OS, filesystem, subprocess & CLIs