Argparse subparameter: hide metavar in the command list

I am using the argparse Python 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. I am currently getting 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 

Is there any way to remove the <command> in the list of subcommands and save it in the usage line? I tried giving help = argparse.SUPPRESS as the add_subparsers argument, but that just hides all the subcommands in the help output.

+8
python argparse
source share
1 answer

I solved this by adding a new HelpFormatter that simply deletes the line if the PARSER action is formatted:

 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 
+10
source share

All Articles