So i'm trying to build an CLI with the following pattern:
cli.py api new --config config.json
or
cli.py api del [api_name]
To achieve the api
i've added it as sup parser
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog='my prog')
subparsers = parser.add_subparsers(title='api', help='available actions')
api_parser = subparsers.add_parser('api')
from here i thought that we might want to add two new subparsers to handle the new
and del
subcommands:
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog='my prog')
subparsers = parser.add_subparsers(title='api', help='available actions')
api_parser = subparsers.add_parser('api')
api_new_subparsers = api_parser.add_subparsers(title='new', help='%(prog)s creates new api gateway')
api_del_subparsers = api_parser.add_subparsers(title='del', help='%(prog)s deletes an api gateway')
but i got the error: cannot have multiple subparser arguments
I've searched a bit. Most of the questions are about the following pattenr cli.py cmdA
and cli.py cmdB
. So i started thinking that argparse maybe is not able to achieve such kind of "depth"?
Thanks a lot.
First, I'm not sure you understand the purpose of the
title
parameter.All
title
does is define a group in the help. It doesn't change parsing. Defining adest
instead oftitle
(or in addition to):This identifies the subparser command in the
args
namespace.But on to the question of multiple subparsers -
argparse
does not allow you to define that. You can nest them. That is you could useBut before you get too far in that direction, have you tried adding plain arguments the
api_parser
? Help display gets messy the deeper you go with subparsers.Or may be you don't need the full subparser mechanism. For example defining two positionals with choices: