1

I am trying to parse multiple groups of arguments in one command line. both setup1 and setup2 can have identical arguments

python3 setup1 --param1 1 --param2 0 setup2 --param1 0 --param2 -1

I tried to use the subparse as below, but it appears it can be used for only one set of subparameters at a time.

does anyone have any hint on how I could do this?

import argparse
import sys

def do_parse_args(argv):
    parser = argparse.ArgumentParser(description='Multiple subparsers')

    subparsers = parser.add_subparsers(dest='command')
    setup1 = subparsers.add_parser('setup1', help='parameters for setup1')
    setup1.add_argument(
        '--param1',
        action='store'
    )

    setup1.add_argument(
        '--param2',
        action='store'
    )

    setup2 = subparsers.add_parser('setup2', help='parameters for setup2')
    setup2.add_argument(
        '--param1',
        action='store'
    )

    setup2.add_argument(
        '--param2',
        action='store'
    )

    return parser.parse_args(argv)


def main(argv=None):
    args = do_parse_args(argv)
    ret = 0

    print(args)

    return ret


if __name__ == "__main__":
    sys.exit(main())
(venv_cvaas) C:\Work\python_hello>python hello.py setup2 --param1 1 setup1 --param1 1
usage: hello.py [-h] {setup1,setup2} ...
hello.py: error: unrecognized arguments: setup1

(venv_cvaas) C:\Work\python_hello>python hello.py setup1 --param1 1 setup2 --param2 0
usage: hello.py [-h] {setup1,setup2} ...
hello.py: error: unrecognized arguments: setup2
James Z
  • 12,209
  • 10
  • 24
  • 44
brane
  • 585
  • 6
  • 20
  • 1
    `subparsers` is a `positional` argument. Once that's provided with `setup2`, the parsing action is passed to that subparser. Anything the subparser can't handle is `unrecognized`. The main parser does not resume parsing. `argparse` does not provide a way of doing multiple groups of arguments. – hpaulj Nov 26 '20 at 17:21

0 Answers0