1

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!

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.