PythiloLesson 8 of 15 · progress kept in this browser

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.
  • type is called on the text. A function that raises argparse.ArgumentTypeError adds your own validation.
  • action="store_true" makes a flag that takes no value. --dry-run is read back as args.dry_run.
  • Bad input prints the usage and raises SystemExit with status 2.
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.