Command-line programs
A script becomes a tool when it takes arguments instead of values edited into its code. argparse reads them, converts their types, writes the --help text, and rejects bad input with a clear message.
import argparse
parser = argparse.ArgumentParser(
prog="backup")
parser.add_argument("source")
parser.add_argument("--keep", type=int,
default=3)
parser.add_argument("--dry-run",
action="store_true")
args = parser.parse_args(
["docs", "--keep", "5"])
print(args.source, args.keep, args.dry_run)- A bare name is a required positional argument. A name starting with
--is an option. typeis called on the text. A function that raisesargparse.ArgumentTypeErroradds your own validation.action="store_true"makes a flag that takes no value.--dry-runis read back asargs.dry_run.- Bad input prints the usage and raises
SystemExitwith status 2.
Keep argv a parameter
Write main(argv=None) and call parser.parse_args(argv) inside it. With None it reads sys.argv, and a test can pass a list instead.
Your task
Write build_parser() returning an ArgumentParser with prog="backup", a positional source, --dest defaulting to "backups", --keep defaulting to 3, and a --dry-run flag. --keep accepts only whole numbers of at least 1: write positive_int(text) for its type, raising argparse.ArgumentTypeError otherwise.
The explanation opens here once every check passes.