Changing the metavar value in argparse only in argument listing and not in its Usage

后端 未结 2 745
情话喂你
情话喂你 2021-01-16 00:07

My question is similar to argparse help without duplicate ALLCAPS question.

Though i would explain in brief what that question was and what my question is:
I\'d

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-16 01:06

    https://stackoverflow.com/a/9643162/901925 and https://stackoverflow.com/a/23941599/901925 and https://stackoverflow.com/a/16969505/901925

    give a HelpFormatter._format_action_invocation(self, action) method modification that replaces '-i INI, --ini INI' with '-i, --ini INI'.

    '-h, --help' doesn't have the CAPS string because help does not take an argument. The INI is just a place holder for that argument. The original just tries to be clear, you can use either -i 124 or --ini 124

    The METAVAR parameter gives you control over that place holder, but it is used both in formatting the usage and the help.

    If you don't want to go the custom HelpFormatter class route, you could still use the custom usage method. For example at some point during development, do usage = parser.format_usage(). Now change the parser so the metavar is '', and the usage is this new one.

    parser = argparse.ArgumentParser()
    a1 = parser.add_argument('-f','--foo',help=' argument')
    a2 = parser.add_argument('-b','--bar',metavar='CUSTOM',help=' argunent')
    a3 = parser.add_argument('-z','--baz', action='store_true', help='no argument')
    
    usage = parser.format_usage()
    parser.usage=usage   # grab original usage
    for a in [a1,a2]:
        a.metavar=''   # 'blank' out the metavars that matter
    parser.print_help()
    

    produces:

    usage: usage: stack30704631.py [-h] [-f FOO] [-b CUSTOM] [-z]
    
    optional arguments:
      -h, --help   show this help message and exit
      -f , --foo    argument
      -b , --bar    argunent
      -z, --baz    no argument
    

提交回复
热议问题