2013-03-26 99 views
2

我写一个程序,如:Python:如何在使用argparse的subparser中拥有互斥组?

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) 

正如所解释的,当我运行--in--out之间TASK1需要一个而不是两个。 如何将此功能添加到我的程序?

回答

3

Subparsers支持所有的方法,一个正常的解析器支持,包括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 
+0

我很抱歉,但什么是_SetAction的作用? (无论如何,谢谢你的回答,我试图让它工作)。 另外,你知道如何在func1中,我只能导入p1sub解析器(+主解析器之一)的参数值而不是p2sub解析器的参数值? – lucacerone 2013-03-26 20:33:13

+0

'_SetAction'?也许你会''StoreTrueAction'吗?它是'add_argument()'调用的返回值,由Python解释器响应。 – 2013-03-26 20:35:34

+0

不确定您的意思是“只导入p1sub解析器参数的值”*。 'parser.parse_args()'函数只返回匹配子解析器参数的值。 – 2013-03-26 20:36:45