liveBook · Manning

Argparse

As explained in The Quick Python Book, Fourth Edition

argparse is Python's standard-library module for parsing command-line arguments and generating related help and error messages.

argparse is Python’s standard-library module for parsing command-line arguments. It handles positional arguments and options, converts values, and generates usage and error messages. section 11.1.5

Create an ArgumentParser, define arguments with add_argument(), and call parse_args(). The result is a namespace whose values are available as attributes, such as args.indent. section 11.1.5

Common argument settings:

  • A positional argument such as "indent" is required by default. Set type=int to convert it to an integer. section 11.1.5
  • An option such as "-f", "--file" can have short and long names. dest="filename" stores its value as args.filename; without a supplied value or another default, it is None. section 11.1.5
  • Use action="store_true" for a flag that becomes True when supplied, or action="store_false" for one that becomes False. Set default to control its value when absent. section 11.1.5 section 11.5.2
  • Use help to describe an argument and metavar to name its value in usage messages. Invalid input or missing required arguments produces an error and usage information. section 11.1.5

Parsing options and positional arguments

For a script defining -x, -q, -f, indent, and input_file, the command `python opts.py -x100 -q -f outfile 2 arg2` produces `Namespace(indent=2, input_file='arg2', filename='outfile', xray='100', verbose=False)`. The integer conversion applies to indent; xray remains a string. 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()

See the complete parser configuration for the command above, including option aliases, destinations, defaults, and help strings. section 11.1.5

Parsing flags is only part of an application’s behavior. In a wc-like utility, -l, -w, and -c select counts; when none of those or -L is supplied, the program selects the standard line, word, and character counts. The longest-line count requires -L. A check with any() can detect whether any selection flag is true. section 11.5.2

Accept a filename or standard input

Define a zero-or-one filename argument with `parser.add_argument('file', nargs='?', type=argparse.FileType('r'), default=sys.stdin)`, after importing argparse and sys. A supplied filename is opened for reading; otherwise args.file is sys.stdin. Processing can then read from the same file-like object in either case. section 13.10.2 section 13.10

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Demonstrates parser setup, conversion, flags, defaults, errors, and file input, without examining parser internals.
Examples
Uses an options parser and a wc-like counting utility, including a filename-or-stdin variant.
What you can do after
Apply it via argparse to configure a parser, retrieve values, and accept a file or standard input.
How it connects
Connects command-line arguments with standard input, input redirection, file handling, and namespace attributes.

Also explained in

Compare how 3 books explain argparse →

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.