`ArgumentParser` is the `argparse` class used to define and read a Python script’s command-line arguments. Create a parser, register arguments with `add_argument()`, then call `parse_args()`. The result is a namespace whose values are available as attributes, such as `args.indent`. section 11.1.5
Listing 11.4 File opts.py
from argparse import ArgumentParser
def main():
parser = ArgumentParser()
parser.add_argument("indent", type=int, help="indent for report")
parser.add_argument("input_file",
help="read data from this file") #1
parser.add_argument("-f", "--file",
dest="filename", #2
help="write report to FILE", metavar="FILE")
parser.add_argument("-x", "--xray",
help="specify xray strength factor")
parser.add_argument("-q", "--quiet",
action="store_false", dest="verbose",
default=True, #3
help="don't print status messages to stdout")
args = parser.parse_args()
print("arguments:", args)
if __name__ == "__main__":
main()
The complete `opts.py` example defines two required positional arguments, three options, and a call to `parse_args()`. section 11.1.5
The argument definitions control how each value is read:
- `indent` and `input_file` are required positional arguments. `type=int` requires `indent` to be convertible to an integer. section 11.1.5
- Names beginning with `-`, such as `-f` and `--file`, define options. `dest="filename"` selects the resulting attribute name; `metavar="FILE"` supplies a name for its value in usage information. section 11.1.5
- `-q` uses `action="store_false"` with `default=True`: supplying it sets `args.verbose` to `False`. An option expecting a value, such as `-x`, instead stores that value. section 11.1.5
Reading a command line
Running `python opts.py -x100 -q -f outfile 2 arg2` produces `Namespace(indent=2, input_file='arg2', filename='outfile', xray='100', verbose=False)`. The parser converts `2` because `indent` specifies `type=int`; `xray` remains a string because no conversion type is specified for it. section 11.1.5
Missing required arguments or an invalid option make `parse_args()` report an error. Its usage line also shows the accepted form, including optional `-h` help and the required positional names. An option not supplied can have a `None` value unless a different default is configured. section 11.1.5
Choosing default output
A `wc`-style program uses `store_true` options for line, word, character, and longest-line counts. When no count option is selected, it prints the standard line, word, and character counts; `-L` must be explicitly selected. Checking the parsed flags with `any()` distinguishes that default case from requests for particular counts. section 11.5.2
