Chapter XIV: application building blocks -argparse: command line options and arguments parsing - parser organization - the principle of shared parser

14.1.6 parser organization
argparse includes a lot of features for organizing parameter parser to implement or improve the availability of help output.

14.1.6.1 sharing principle parser
programmers often need to implement a set of command-line tools, they take a set of parameters, and then perform certain specialized operation. For example, if the program before taking concrete action needs to authenticate the user, then they need to support -user and -password options. Without explicitly added to each of these options ArgumentParser, you can use these options to define a shared parent parser, and then let the parser for each program inherits the parent parser options.
The first step is to create a shared parameter defines the parser. Since each subsequent users parent parser will try to help increase the same options, which can lead to an exception, so to turn off the automatic help generate the base parser.

import argparse

parser = argparse.ArgumentParser(add_help=False)

parser.add_argument('--user',action="store")
parser.add_argument('--password',action="store")

Next, create a collection with gparents another parser.

import argparse
import argparse_parent_base

parser = argparse.ArgumentParser(
    parents=[argparse_parent_base.parser],
    )

parser.add_argument('--local-arg',
                    action="store_true",
                    default=False)

print(parser.parse_args())

The resulting program will have three options.
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_43193719/article/details/93121881