Argparse subparser: hide metavar in command listing
argparse, python
Solution
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
Problem
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.