nested subparsers with argparse

2010-08-23 Thread Chris Withers

Hi All,

I'm looking to build a script that has command line options as follows:

./myscript.py command subcommand [options]

I can do up to the command [options] bit with add_subparsers in 
argparse, but how do I then add a second level of subparsers?


cheers,

Chris

--
http://mail.python.org/mailman/listinfo/python-list


Re: nested subparsers with argparse

2010-08-23 Thread Chris Withers

Chris Withers wrote:

Hi All,

I'm looking to build a script that has command line options as follows:

./myscript.py command subcommand [options]

I can do up to the command [options] bit with add_subparsers in 
argparse, but how do I then add a second level of subparsers?


Answering my own question, here's what worked for me:


from argparse import ArgumentParser
from mock import Mock

m = Mock()

parser = ArgumentParser()
subparsers = parser.add_subparsers()

agroup = subparsers.add_parser('a')

command = subparsers.add_parser('b')
command.set_defaults(func=m.b)

subparsers = agroup.add_subparsers()
command = subparsers.add_parser('aa')
command.set_defaults(func=m.a.a)

command = subparsers.add_parser('ab')
command.set_defaults(func=m.a.b)

options = parser.parse_args()

options.func(options)

print m.method_calls


If there's anything I could have done better, please let me know!

Chris

--
http://mail.python.org/mailman/listinfo/python-list


Re: nested subparsers with argparse

2010-08-23 Thread Peter Otten
Chris Withers wrote:

 I'm looking to build a script that has command line options as follows:
 
 ./myscript.py command subcommand [options]
 
 I can do up to the command [options] bit with add_subparsers in
 argparse, but how do I then add a second level of subparsers?

It looks like subparsers behave like the toplevel parsers -- you can invoke 
add_subparsers() on them, too.
-- 
http://mail.python.org/mailman/listinfo/python-list