Nested subparsers?

1,469 views
Skip to first unread message

MaxB

unread,
Jun 11, 2011, 8:09:56 AM6/11/11
to argparse-users, ma...@redhat.com
Hi Steven,

How can I use the argparse in this way:
>> prog option1 {only cmd1 and cmd2 are available}
>> prog option2 {only cmd3 and cmd4 are available}

NOTE: each cmd{#} defined as a subparser with its unique set of
parameters.

It's close to the behavior of "svn commit" for example with an
addition of a mandatory
parameter before any subparser, this parameter determines which
subparser to call, say:
"svn local commit" is legal but if "remote" is used instead of "local"
the "commit" option
won't be available at all and the user may use "svn remote copy" for
example.

I tried to define nested subparsers but got: "cannot have multiple
subparser arguments".
May be I'm missing something but currently I'm unable to reach the
desired behavior.

TIA,
MaxB.

Steven Bethard

unread,
Jun 14, 2011, 5:48:12 AM6/14/11
to argpars...@googlegroups.com, ma...@redhat.com
On Sat, Jun 11, 2011 at 2:09 PM, MaxB <max.be...@gmail.com> wrote:
> How can I use the argparse in this way:
>>> prog option1 {only cmd1 and cmd2 are available}
>>> prog option2 {only cmd3 and cmd4 are available}

Perhaps I don't understand the question, but I would just call
add_subparsers() on the main parser, and then again call
add_subparsers() on each of the child parsers you create, e.g.:

main_parser = argparse.ArgumentParser()
main_subparsers = main_parser.add_subparsers()
option1_parser = main_subparsers.add_parser('option1')
option1_subparsers = option1_parser.add_subparsers()
option1_subparsers.add_parser('cmd1')
option1_subparsers.add_parser('cmd2')
option2_parser = main_subparsers.add_parser('option2')
option2_subparsers = option2_parser.add_subparsers()
option2_subparsers.add_parser('cmd3')
option2_subparsers.add_parser('cmd4')
main_parser.parse_args()

Steve
--
Where did you get that preposterous hypothesis?
Did Steve tell you that?
        --- The Hiphopopotamus

Reply all
Reply to author
Forward
0 new messages