I'm using ArgumentParser
to document the usage of a complicated program. Since the program has several long lists of capabilities, it requires several --help
arguments.
My current ArgumentParser
looks like this.
parser = ArgumentParser(description = 'Complicated program')
parser.add_argument('--list-models', action = 'store_true', help = 'List the available models')
parser.add_argument('--list-stuff', action = 'store_true', help = 'List the other stuff')
# ...
parser.add_argument('important_data', help = 'Some important data that is required')
I want --list-models
and --list-stuff
to print some data and exit, similar to how --help
works.
However, running the program with either argument fails since important_data
is a positional argument, which ArgumentParser
always requires.
What's the nicest way to implement this help pattern?
My approach is to make --important-data
optional and check afterward:
from argparse import ArgumentParser
import sys
parser = ArgumentParser(description="Complicated program")
parser.add_argument(
"--list-models", action="store_true", help="List the available models"
)
parser.add_argument("--list-stuff", action="store_true", help="List the other stuff")
# ...
parser.add_argument(
"important_data", nargs="?", help="Some important data that is required"
)
options = parser.parse_args()
print(f"{options=}")
if options.important_data is None and not options.list_models and not options.list_stuff:
parser.print_help()
sys.exit(1)
if options.list_models:
print("list models")
sys.exit(0)
if options.list_stuff:
print("list stuff")
sys.exit(0)
# The rest of the code