1

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!

user13581602
  • 105
  • 1
  • 9
  • 1
    https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_subparsers – dosas May 12 '21 at 09:37

1 Answers1

1

Thanks @PhilippSelenium for pointing out the link to the docs.

I solved this by removing parents=[parent_parser] from subparsers.add_parser()

user13581602
  • 105
  • 1
  • 9
  • 1
    using the parents created a kind of recursive subparser mechanism expecting `prog.py run run run ...` – hpaulj May 12 '21 at 10:24