带有至少一个必需参数的可选参数

时间:2017-03-12 11:00:47

标签: python argparse

我希望我的程序有一个可选参数,但是当给出该选项时,该选项需要至少有一个参数。所以帮助热线应该是这样的:

myprog [file] [-a] [-b] [--optionalArgument neededParameter [optionalParameter ...]]

如何使用argparse存档?

1 个答案:

答案 0 :(得分:1)

例如:

parser = ArgumentParser()
parser.add_argument('-a', action='store_true')
parser.add_argument('--optional', nargs='+', metavar=('neededParameter', 'optionalParameter'))

这将需要--optional的一个或多个参数,并且使用消息将打印为:

usage: args.py [-h] [-a] [--optional neededParameter [optionalParameter ...]]