With argparse are subparsers inherently mutually exclusive?

断了今生、忘了曾经 提交于 2019-12-04 20:14:54

Yes, they are mutually exclusive, though the mechanism is different from the MXGroups.

subparser = parser.add_subparsers(help='sub-command help')

is an add_argument command that creates a positional argument, with a special action class. Among other things it has a choices value.

subparser.add_parser(...)

creates a parser, and adds its 'name' (and aliases) to subparser's choices.

A positional argument is parsed only once, so only one subparser will be handled. And the subparser usually processes all of the remaining arguments.

There have been SO questions that ask about getting around that - that is they want to handle multiple subparsers. The way to do that is tricky, and involves calling a parser recursively (or repeatedly), each time with a smaller set of the original arguments.

As far as I can tell subparsers are mutually exclusive by default:

Note that the object returned by parse_args() will only contain attributes for the main parser and the subparser that was selected by the command line (and not any other subparsers). So in the example above, when the a command is specified, only the foo and bar attributes are present, and when the b command is specified, only the foo and baz attributes are present.

From the python documentation on subparsers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!