Argparse: parse multiple subcommands
<p>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:</p>

<pre><code>./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
</code></pre>

<p>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'</p>

<p>Any solution?</p>

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

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

<ul>
<li><p><code>add_subparsers</code> creates a positional argument; unlike <code>optionals</code> a `positional acts only once.</p></li>
<li><p>'add_subparsers' raises an error if you invoke it several times</p></li>
<li><p>the parsing is built around only one such call</p></li>
</ul>

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

<p>Or you can detect and call multiple parsers, bypassing the <code>subparser</code> mechanism.</p>

<p>From the sidebar</p>

<p><a href="http://stackoverflow.com/questions/24484035/multiple-invocation-of-the-same-subcommand-in-a-single-command-line">Multiple invocation of the same subcommand in a single command line</a></p>

<p>and</p>

<p><a href="http://stackoverflow.com/questions/31559910/parse-multiple-subcommands-in-python-simultaneously-or-other-way-to-group-parsed">Parse multiple subcommands in python simultaneously or other way to group parsed arguments</a></p>

python argparse subcommand subparsers