我正在使用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)
答案 0 :(得分:1)
add_mutually_exclusive_group()的当前实现实际上并不存在 创建互斥的群组。有open bug来解决此问题。
话虽如此,您可以使用以下方式实现此目的:
(a)subcommands
示例代码:
# 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."