Reputation: 772
Given the following code snippet:
import argparse
import sys
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help="subcommand help")
command1 = subparsers.add_parser("foo", description="Run foo subcommand")
command2 = subparsers.add_parser("bar", description="Run bar subcommand")
opts = parser.parse_args(sys.argv[1:])
When I print help for this I get this:
usage: test.py [-h] {foo,bar} ...
positional arguments:
{foo,bar} subcommand help
optional arguments:
-h, --help show this help message and exit
Is there a way to make it print something like this instead:
usage: test.py [-h] {foo,bar} ...
subcommands:
foo Run foo subcommand
bar Run bar subcommand
optional arguments:
-h, --help show this help message and exit
without supplying a custom formatter? If I change the formatter then it also changes everything else about how the help is printed, but in my case I just want to change the way that subcommand help is printed from the parent (sub)command.
Upvotes: 5
Views: 890
Reputation: 7040
You need to set the help
parameter, not the description
parameter, to get the output you desire:
import argparse
import sys
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help="subcommand help")
command1 = subparsers.add_parser("foo", help="Run foo subcommand")
command2 = subparsers.add_parser("bar", help="Run bar subcommand")
opts = parser.parse_args(sys.argv[1:])
Output:
usage: test.py [-h] {foo,bar} ...
positional arguments:
{foo,bar} subcommand help
foo Run foo subcommand
bar Run bar subcommand
optional arguments:
-h, --help show this help message and exit
The argparse docs have this to say about the help value:
The help value is a string containing a brief description of the argument. When a user requests help (usually by using -h or --help at the command line), these help descriptions will be displayed with each argument.
And this to say to about the description value:
This argument gives a brief description of what the program does and how it works. In help messages, the description is displayed between the command-line usage string and the help messages for the various arguments.
Upvotes: 6