Argparse: parse multiple subcommands

守給你的承諾、 提交于 2019-12-11 05:05:56

问题


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



来源:https://stackoverflow.com/questions/39644246/argparse-parse-multiple-subcommands

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