liveBook · Manning

Argument parser

As explained in The Quick Python Book, Fourth Edition

ArgumentParser is the argparse class that represents a command-line argument parser and defines how arguments are recognized and converted.

`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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through parser setup, argument definitions, namespace values, and error output, then applies option defaults in a word-count program.
Examples
Demonstrates `opts.py` with positional values and switches, then uses a `wc`-style program to test combinations of count options.
What it assumes
Assumes familiarity with Python scripts and function calls while showing `argparse` setup in a complete small script.
What you can do after
Build it from scratch for a Python script with typed positional inputs, options, and conditional output based on parsed flags.
How it connects
Connects command-line arguments to `argparse`, type conversion, namespaces, default values, and usage messages.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.