Conceptual grouping of arguments with argparse.add argument group
suggest changeWhen you create an argparse ArgumentParser() and run your program with -h you get an automated usage message explaining what arguments you can run your software with. By default, positional arguments and options are separated into two categories, for example, here is a small script (example.py) and the output when you run python example.py -h.
import argparse
parser = argparse.ArgumentParser(description='Simple example')
parser.add_argument('name', help='Who to greet')
parser.add_argument('--bar_this')
parser.add_argument('--bar_that')
parser.add_argument('--foo_this')
parser.add_argument('--foo_that')
args = parser.parse_args()
usage: example.py [-h] [--bar_this BAR_THIS] [--bar_that BAR_THAT]
[--foo_this FOO_THIS] [--foo_that FOO_THAT]
name
Simple example
positional arguments:
name Who to greet
options:
-h, --help show this help message and exit
--bar_this BAR_THIS
--bar_that BAR_THAT
--foo_this FOO_THIS
--foo_that FOO_THAT
There are some situations where you want to separate your arguments into further conceptual sections to assist your user. For example, you may wish to have all the input options in one group, and all the output formatting options in another. The above example can be adjusted to separate the --foo_* args from the --bar_* args like so.
import argparse
parser = argparse.ArgumentParser(description='Simple example')
parser.add_argument('name', help='Who to greet')
# Create two argument groups
foo_group = parser.add_argument_group(title='Foo options')
bar_group = parser.add_argument_group(title='Bar options')
# Add arguments to those groups
foo_group.add_argument('--foo_this')
foo_group.add_argument('--foo_that')
bar_group.add_argument('--bar_this')
bar_group.add_argument('--bar_that')
args = parser.parse_args()
Which produces this output when python example.py -h is run:
usage: example.py [-h] [--foo_this FOO_THIS] [--foo_that FOO_THAT]
[--bar_this BAR_THIS] [--bar_that BAR_THAT]
name
Simple example
positional arguments:
name Who to greet
options:
-h, --help show this help message and exit
Foo options:
--foo_this FOO_THIS
--foo_that FOO_THAT
Bar options:
--bar_this BAR_THIS
--bar_that BAR_THAT
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents