Argparse: parse multiple subcommands

2019-07-24 05:50发布

问题:

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:

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