[issue9253] argparse: optional subparsers

Michael.Elsdörfer report at bugs.python.org
Tue Aug 10 23:06:22 CEST 2010


Michael.Elsdörfer <michael at elsdoerfer.info> added the comment:

To expand on my case from issue9540, I have a bunch of commands, each of which should enable a specific subset of options only available the individual command, but all of the commands share the same behavior in taking nargs='*' positional arguments:

./script.py --global-option command --command-option arg1 arg2 arg3

For example:

./backups.py -c /etc/tarsnap.conf make --no-expire job1 job2

If no positional arguments are given, all jobs defined in the config file are run. Or, in the above example, only "job1" and "job2" are run.

The positional arguments are the same for *all* commands. Now I can define them separately for each subparser, which is what I'm currently doing, but I kind of like having the global usage instructions (script.py -h) indicating the fact that positional arguments can be passed after the command. 

In fact, right now I'm able to sort of achieve this by defining the positional nargs arguments both globally (to have them show in usage) and in each subparser (to have them parsed). This wouldn't be possible anymore if argparse where to throw an error after adding arguments after a subparser, although probably a more correct behavior.

Anyway, while the two issues are clearly related, I don't think that the two are necessarily mutually exclusive. argparse could allow both optional subparsers (if no subparser matches), as well as pass control back to the parent parser once an already matched subparser is no longer able to handle further command line input. Or optionally, support defining subparsers as "options only", so that positional arguments would always be handled by the parent parser.

Now, I can see how this could potentially become messy if we start talking about these positional arguments handled by the parent then being followed by more flags, which would then presumably also be handled by the parent etc. On the other hand, my use case doesn't seem that strange to me.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue9253>
_______________________________________


More information about the Python-bugs-list mailing list