Appendix E — Build a Basic CLI with argparse Answers

Completed Check

The first parser only needs one required value: the fixture-backed domain the tool should test. Passing a list to parse_args() keeps the notebook example stable, while a real script can call parse_args() without arguments and let argparse read from sys.argv.

import argparse


def build_argument_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument("domain", help="fixture-backed domain to test, e.g. example.test")
    return parser


args = build_argument_parser().parse_args(["example.test"])
print(args.domain)
example.test

Here’s what’s happening: argparse owns the user-input parsing, and the rest of the program gets a small object with a domain attribute. That keeps the command-line contract separate from whatever the tool eventually does with the target.

References: argparse and ArgumentParser.add_argument().