I am new to argsparse
thus this might pretty sure be a newbie mistake so please bare with me. My code:
import argsparse
parent_parser = argparse.ArgumentParser(description='Argument Parser')
subparsers = parent_parser.add_subparsers(title="Sub-commands", description='Sub-commands Parser')
parser_create = subparsers.add_parser('run', parents=[parent_parser], add_help=False, help="run the program")
parser_create.add_argument('--program', metavar=('NAME'), required=True, type=str, help='name of the program')
This works perfectly fine when running parser.py run --program 'test'
in the console:
args = parent_parser.parse_args(); print(args)
outputs Namespace(program='test')
However, when I try to replace the optional argument with a positional one like:
parser_create.add_argument('program', metavar=('NAME'), type=str, help='name of the program')
And then run parser.py run 'test'
in the console the following error is raised:
usage: parser.py run [-h] {run} ... NAME
parser.py run: error: invalid choice: 'test' (choose from 'run')
Adding the positional argument to a group results in the same error as above:
required = parser_create.add_argument_group('required positional argument')
required.add_argument('program', metavar=('NAME'), type=str, help='name of the program')
How can I pass positional arguments to the subparser formatted as run <program>
?
I would appreciate any feedback. Thanks!