1

Did some research, but couldn't find any working solution. I'm trying to parse the following command line, where 'test' and 'train' are two independent subcommands each having distinct arguments:

./foo.py train -a 1 -b 2 
./foo.py test  -a 3 -c 4
./foo.py train -a 1 -b 2 test -a 3 -c 4

I've been trying using two subparsers ('test','train') but it seems like only one can be parsed at the time. Also it would be great to have those subparsers parents of the main parser such that, e.g. command '-a' doesn't have to be added both to the subparsers 'train' and 'test'

Any solution?

1
  • You can use parents to add a common argument to several subparsers. Or you can define -a for the main parser. Commented Sep 22, 2016 at 18:38

1 Answer 1

1

This has been asked before, though I'm not sure the best way of finding those questions.

The whole subparser mechanism is designed for one such command. There are several things to note:

  • add_subparsers creates a positional argument; unlike optionals a `positional acts only once.

  • 'add_subparsers' raises an error if you invoke it several times

  • the parsing is built around only one such call

One work around that we've proposed in the past is 'nested' or 'recursive' subparers. In other words train is setup so it too takes a subparser. But there's the complication as to whether subparsers are required or not.

Or you can detect and call multiple parsers, bypassing the subparser mechanism.

From the sidebar

Multiple invocation of the same subcommand in a single command line

and

Parse multiple subcommands in python simultaneously or other way to group parsed arguments

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.