argparse parses command-line arguments for Python scripts and generates usage and error messages. Create an ArgumentParser, declare arguments with add_argument(), then call parse_args(). The result is a Namespace whose values are available as attributes. section 11.1.5
The main argument choices are:
- Positional arguments have no leading hyphen and are required by default. Use type=int when a value must parse as an integer. section 11.1.5
- Optional arguments start with a hyphen; one option can have short and long forms, such as -f and --file. An omitted value-taking option is None unless another default is supplied. section 11.1.5
- Use action="store_true" for a flag that becomes True when supplied. Use action="store_false" with default=True for a flag that turns a setting off. section 11.1.5 section 11.5.2
Parse a report command
Given positional arguments indent and input_file, plus -f/--file and -q/--quiet, the command `python opts.py -q -f outfile 2 arg2` produces values equivalent to `Namespace(indent=2, input_file='arg2', filename='outfile', verbose=False)`. The integer conversion applies to indent; -q switches verbose from its True default to False. Missing required arguments trigger a usage message and an error. 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()
A complete small parser showing positional arguments, option aliases, help text, a destination name, a default, and parse_args(). section 11.1.5
Parsing flags is only part of a command-line program: their combined meaning may need separate logic. For a wc-style utility, -l, -w, and -c select individual counts; when none is selected, the usual counts appear together. The longest-line option, -L, must be requested explicitly. section 11.5.2
Accept a filename or redirected input
Declare `parser.add_argument('file', nargs='?', type=argparse.FileType('r'), default=sys.stdin)`. The `?` allows zero or one filename; FileType opens a supplied file for reading, while no filename leaves sys.stdin as the input. The counting code can then read either file object without opening it again. Omit a filename label from the output when input came from stdin. section 13.10 section 13.10.2


