Code

A Clean Command Line

Good tools have friendly command lines: clear arguments, sensible defaults, helpful --help. argparse gives you all of that:

import argparse

parser = argparse.ArgumentParser(prog="lantern",
                                 description="Light a lantern.")
parser.add_argument("island")                        # positional
parser.add_argument("--fuel", type=int, default=10)  # converted to int
parser.add_argument("--mode", choices=["steady", "blink"],
                    default="steady")
parser.add_argument("--dry-run", action="store_true")  # a flag

args = parser.parse_args(["Ember", "--dry-run"])
args.island, args.fuel, args.dry_run   # 'Ember', 10, True

Notice that --dry-run becomes args.dry_run. Bad input (a wrong choice, --fuel lots) makes argparse print a usage message and exit with SystemExit.

The testable pattern

Professionals write main(argv=None) and pass argv to parse_args. None means "use the real command line", while tests can pass a list. Have main return its result instead of only printing it:

if __name__ == "__main__":
    print(main())

Assignment

  1. Finish build_parser() with --fuel (int, default 10), --mode (choices steady/blink, default steady) and --dry-run (a flag).
  2. Finish main(argv) so it returns "Lighting <island> with <fuel> fuel (<mode>)", with "[dry run] " in front when the flag is set.