Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse subparser: hide metavar in command listing

I'm using the Python argparse module for command line subcommands in my program. My code basically looks like this:

import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title="subcommands", metavar="<command>")

subparser = subparsers.add_parser("this", help="do this")
subparser = subparsers.add_parser("that", help="do that")

parser.parse_args()

When running "python test.py --help" I would like to list the available subcommands. Currently I get this output:

usage: test.py [-h] <command> ...

optional arguments:
  -h, --help  show this help message and exit

subcommands:
  <command>
    this      do this
    that      do that

Can I somehow remove the <command> line in the subcommands listing and still keep it in the usage line? I have tried to give help=argparse.SUPPRESS as argument to add_subparsers, but that just hides all the subcommands in the help output.

like image 754
Jeppe Ledet-Pedersen Avatar asked Nov 16 '12 19:11

Jeppe Ledet-Pedersen


People also ask

What is Metavar in Argparse?

Metavar: It provides a different name for optional argument in help messages. Provide a value for the metavar keyword argument within add_argument() .

How do you add an optional argument in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What does parse_args return?

Adding arguments Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.


1 Answers

I solved it by adding a new HelpFormatter that just removes the line if formatting a PARSER action:

class SubcommandHelpFormatter(argparse.RawDescriptionHelpFormatter):
    def _format_action(self, action):
        parts = super(argparse.RawDescriptionHelpFormatter, self)._format_action(action)
        if action.nargs == argparse.PARSER:
            parts = "\n".join(parts.split("\n")[1:])
        return parts
like image 116
Jeppe Ledet-Pedersen Avatar answered Oct 05 '22 23:10

Jeppe Ledet-Pedersen