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.
More on OS, filesystem, subprocess & CLIs
`os.path` vs `pathlib`: which do you use and why?BeginnerHow do you read environment variables safely?BeginnerHow do you walk a directory tree and find files?BeginnerWhat does `shutil` give you that `os` does not?BeginnerHow do you run an external command correctly with `subprocess`?BeginnerWhy is `shell=True` dangerous, and when is it acceptable?Intermediate