【问题标题】:Python: how to have mutually exclusive groups in subparser using argparse?Python:如何在使用 argparse 的子解析器中拥有互斥组?
【发布时间】:2013-03-16 16:27:36
【问题描述】:

我正在编写一个类似的程序:

import argparse

def task1(args):
    print "running task 1"

def task2(args):
    print "running task 2"


if __name__=="__main__":
    parser=argparse.ArgumentParser(description="How can I have mutually exclusive groups in subparsers?")
    subparsers=parser.add_subparsers()
    t1sub=subparsers.add_parser("task1")
    #....
    t1sub.set_defaults(func=task1)
    # here I would like to have a mutually exclusive group
    # when task 1 of the option one between --in and --out is required, but one excludes the other
    # apparently a subparser has no add_group() not add_mutually_exclusive_group(), though
    t2sub=subparsers.add_parser("task2")
    #....
    t1sub.set_defaults(func=task2)

    args = parser.parse_args()

    args.func(args)

正如我在运行 task1 时所解释的那样,--in--out 之间的一个是必需的,但不是两者都需要。 如何将此功能添加到我的程序中??

【问题讨论】:

    标签: python python-2.7 argparse mutual-exclusion


    【解决方案1】:

    子解析器支持普通解析器支持的所有方法,包括add_mutually_exclusive_group():

    >>> megroup = t1sub.add_mutually_exclusive_group()
    >>> megroup.add_argument('--in', action='store_true')
    _StoreTrueAction(option_strings=['--in'], dest='in', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
    >>> megroup.add_argument('--out', action='store_true')
    _StoreTrueAction(option_strings=['--out'], dest='out', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
    >>> parser.parse_args(['task1', '--in'])
    Namespace(func=<function task1 at 0x10a0d9050>, in=True, out=False)
    >>> t1sub.print_help()
    usage:  task1 [-h] [--in | --out]
    
    optional arguments:
      -h, --help  show this help message and exit
      --in
      --out
    >>> parser.print_help()
    usage: [-h] {task1,task2} ...
    
    How can I have mutually exclusive groups in subparsers?
    
    positional arguments:
      {task1,task2}
    
    optional arguments:
      -h, --help     show this help message and exit
    

    【讨论】:

    • 对不起,_SetAction的作用是什么? (无论如何感谢您的回答,我正在努力使其工作)。另外,您知道如何在 func1 中只导入 p1sub 解析器(+ 主解析器)的参数值,而不是 p2sub 解析器的参数值吗?
    • _SetAction?你是_StoreTrueAction吗?这是add_argument() 调用的返回值,由 Python 解释器回显。
    • 不确定你的意思 'import only the parameters of the p1sub parser'parser.parse_args() 函数只返回匹配子解析器的参数值。
    • 感谢您的帮助!抱歉,我没有注意到这是一个输出。好的,只是最后一个问题,也许您可​​以帮助我..您可以根据 --in --out 标志更改 func 的值吗?在内部我想要一个 f1_in(args) 和一个 f1_out(args).. 我正在尝试你的解决方案,如果它有效,我会投票给它.. 我尝试使用子解析器和相互排斥的组,但它没有不起作用,也许我使用了错误的语法..
    • 非常感谢!这实际上帮助了我很多。如果问题很琐碎,我很抱歉,我发现官方文档有点难以消化..
    猜你喜欢
    • 1970-01-01
    • 2021-12-20
    • 2020-06-19
    • 2011-12-13
    • 2011-06-09
    • 2020-07-29
    • 2018-12-31
    • 1970-01-01
    相关资源
    最近更新 更多