Chapter XIV: application building blocks -argparse: parsing command line options and parameters - help output - customized help

14.1.5.2 customized help
for the need to deal directly with the help of application output, ArgumentParser provides some tools useful way, you can create custom actions to help print contains additional information.

import argparse

parser = argparse.ArgumentParser(add_help=True)

parser.add_argument('-a',action="store_true",default=False)
parser.add_argument('-b',action="store",dest="b")
parser.add_argument('-c',action="store",dest="c",type=int)

print('print_usage output:')
parser.print_usage()
print()

print('print_help output:')
parser.print_help()

print_usage () will print a short usage message as a parameter parser, print_help () will print the complete help output.
Here Insert Picture Description
ArgumentParser using a formatter class to help control the output appearance. To change this class, you can pass formatter_class at instantiation ArgumentParser.

import argparse

parser = argparse.ArgumentParser(
    add_help=True,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description="""
    description
        not
            warpped""",
    epilog="""
    epilog
        not
            wrapped"""
    )

parser.add_argument(
    '-a',action="store_true",
    help="""argument
    help is
    wrapped
    """,
    )

parser.print_help()

Command descriptions and all documents are saved in the epilog unchanged.
Here Insert Picture Description
RawTextHelpFormatter will all help text is treated as if it had been pre-formatted the same.

import argparse

parser = argparse.ArgumentParser(
    add_help=True,
    formatter_class=argparse.RawTextHelpFormatter,
    description="""
    description
        not
            warpped""",
    epilog="""
    epilog
        not
            wrapped"""
    )

parser.add_argument(
    '-a',action="store_true",
    help="""argument
    help is not
    wrapped
    """,
    )

parser.print_help()

-A parameter corresponding to the help files will not properly wrap.
Here Insert Picture Description
Some applications or epilog described in some examples, the text format may make changes to these examples are no longer valid, for these applications, the raw format may be useful. MetavarTypeHelpFormatter will print the name of each option type, instead of the target variable, for which there are
a large number of applications of different types of options may be useful.

import argparse

parser = argparse.ArgumentParser(
    add_help=True,
    formatter_class=argparse.MetavarTypeHelpFormatter,
    )

parser.add_argument('-i',type=int,dest='notshown1')
parser.add_argument('-f',type=float,dest="notshown2")

parser.print_help()

Dest value is not displayed, but will print the name of the type associated with the options.
Here Insert Picture Description

Guess you like

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