nested subparsers with argparse

Chris Withers chris at
Mon Aug 23 16:19:30 CEST 2010

Chris Withers wrote:
> Hi All,
> I'm looking to build a script that has command line options as follows:
> ./ 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')

subparsers = agroup.add_subparsers()
command = subparsers.add_parser('aa')

command = subparsers.add_parser('ab')

options = parser.parse_args()


print m.method_calls

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


More information about the Python-list mailing list