Nested ArgumentParser

可紊 提交于 2020-01-05 12:07:39

问题


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:


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()


来源:https://stackoverflow.com/questions/23178097/nested-argumentparser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!