Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Argparse add_mutual_exclusive_group()-需要2个参数或1个参数_Python_Arguments - Fatal编程技术网

Python Argparse add_mutual_exclusive_group()-需要2个参数或1个参数

Python Argparse add_mutual_exclusive_group()-需要2个参数或1个参数,python,arguments,Python,Arguments,我正在使用Python的2.7 argparse。我需要它,用户可以在其中输入参数(-a和-b)或(-c)。但不是(-a和-b)和(-c)在一起。如果用户选择(-a和-b)而不是-c,则两者都是必需的。我怎么能这样做 group_key = member_add.add_mutually_exclusive_group(required=True) group_key.add_argument('-a', required=True) group_

我正在使用Python的2.7 argparse。我需要它,用户可以在其中输入参数(-a和-b)或(-c)。但不是(-a和-b)和(-c)在一起。如果用户选择(-a和-b)而不是-c,则两者都是必需的。我怎么能这样做

group_key = member_add.add_mutually_exclusive_group(required=True)
group_key.add_argument('-a',
                       required=True)

group_key.add_argument('-b',
                         required=True)

group_key.add_argument('-c',
                         required=True)

add_mutual_exclusive_group()的当前实现实际上没有 创建相互排斥的组。有一种方法可以解决这种行为

话虽如此,您可以通过以下方式实现:

(a)

示例代码:

# create the top-level parser
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='help for subcommand')

# create the parser for the "cmd_1" command
parser_a = subparsers.add_parser('cmd_1', help='help for cmd_1')
parser_a.add_argument('-a', type=str, help='help for a')
parser_a.add_argument('-b', type=str, help='help for b')

# create the parser for the "cmd_2" command
parser_b = subparsers.add_parser('cmd_2', help='help for cmd_2')
parser_b.add_argument('-c', type=str,  help='help for c')
parser.parse_args()
(b) 针对像您这样的简单案例的小技巧:

ap=argparse.ArgumentParser()

# 1st group
ap.add_argument("-a", dest="value_a",  help="help for a", required=False)
ap.add_argument("-b", dest="value_b",  help="help for b", required=False)

# 2nd group
ap.add_argument("-c",  dest="value_c", help="help for b", required=False)
args = ap.parse_args()

if (args.value_a or args.value_b):
if (args.value_a or args.value_b) and args.value_c:
    print "-a and -b|-c are mutually exclusive ..."
elif not (args.value_a and args.value_b):
    print "both -a and -b are required."