Kurt Spindler
Kurt Spindler

Reputation: 1321

Nested ArgumentParser

I'm trying to build nested parsers for a command line tool. I'm currently using add_subparsers, but it seems not powerful enough for one specific case. I cannot add same named arguments to both the parent parser and subparser commands. See the following example:

import argparse

argparser = argparse.ArgumentParser()
argparser.add_argument("-H", action="store_true")
subparser = argparser.add_subparsers(dest='sp')
cmd = subparser.add_parser("cmd")
cmd.add_argument("-H")

print argparser.parse_args()

Then, running

py test.py -H cmd -H 5

on the command line gives

Namespace(H='5', sp='cmd')

I'd hope to instead have something perhaps like

Namespace(H=True, sp={'cmd':Namespace(h='5')})

Is there a native way to get something like this functionality, or do I have to go through the trouble of building a custom argparser? Thanks!

Upvotes: 1

Views: 569

Answers (1)

hpaulj
hpaulj

Reputation: 231365

I think your question is answered here:

argparse subcommands with nested namespaces

One of my answers uses a custom action.

But a simpler way of handling duplicate argument names, is to give one, or both, different 'dest' values. It distinguishes between the two without extra machinery.

argparser = argparse.ArgumentParser()
argparser.add_argument("-H", action="store_true")
subparser = argparser.add_subparsers(dest='sp')
cmd = subparser.add_parser("cmd")
cmd.add_argument("-H", dest='cmd_H')

print argparser.parse_args()

Upvotes: 3

Related Questions