argparse: how to get command name for subparsers

George Shuklin
Aug 24, 2017 · 1 min read

Python’s documentation for argparse module is a bit overwhelming yet incomplete.

I had had problem using subparsers: docs proposed a way which was inconvenient:

>>> # sub-command functions
>>> def foo(args):
... print(args.x * args.y)
...
>>> def bar(args):
... print('((%s))' % args.z)
...
>>> # create the top-level parser
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers()
>>>
>>> # create the parser for the "foo" command
>>> parser_foo = subparsers.add_parser('foo')
>>> parser_foo.add_argument('-x', type=int, default=1)
>>> parser_foo.add_argument('y', type=float)
>>> parser_foo.set_defaults(func=foo)
>>>
>>> # create the parser for the "bar" command
>>> parser_bar = subparsers.add_parser('bar')
>>> parser_bar.add_argument('z')
>>> parser_bar.set_defaults(func=bar)
>>>
>>> # parse the args and call whatever function was selected
>>> args = parser.parse_args('foo 1 -x 2'.split())
>>> args.func(args)
2.0
>>>

I don’t want to use so many ‘sub-command’ functions, I want to use a few if’s to check which subparser was used.

Dest argument

I found that add_subparsers function accepts ‘dest’ argument, and that argument contains the selected subparser:

subparsers = parser.add_subparsers(title="commands", dest="command")
...
args = parser.parse_args(command_line)
if args.command == 'command_one':
...
elif args.command == 'command_two':
...

Simple, convenient, yet omitted from docs.

)

George Shuklin

Written by

I work at Servers.com, most of my stories are about Ansible, Ceph, Python, Openstack and Linux.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade