Python 可选参数对 [英] Python Optional Argument Pair
问题描述
我正在使用 argparse
模块来获取两个可选的命令行参数:
I'm using the argparse
module to get two optional command line arguments:
parser.add_argument('start_date', nargs='?', metavar='START DATE',
help='start date in YYYY-MM-DD')
parser.add_argument('end_date', nargs='?', metavar='END DATE',
help='end date in YYYY-MM-DD')
给出
> python test_arg.py -h
usage: test_arg.py [-h] [START DATE] [END DATE]
但是,我希望将一对可选参数(START DATE
和 END DATE
)(如果有的话)一起提供.类似这样的事情:
However I want the pair of optional arguments (START DATE
and END DATE
), if provided at all, to be provided together. Something like along this line:
usage: test_arg.py [-h] [START_DATE END_DATE]
是否可以使用 argparse
?
推荐答案
我能想到的最接近的是:
The closest I can come up with is:
parser=argparse.ArgumentParser()
parser.add_argument('--dates', nargs=2, metavar=('START DATE','END_DATE'),
help='start date and end date in YYYY-MM-DD')
print(parser.format_help())
产生
usage: stock19805170.py [-h] [--dates START DATE END_DATE]
optional arguments:
-h, --help show this help message and exit
--dates START DATE END_DATE
start date and end date in YYYY-MM-DD
没有一种方法可以指定 - '需要将这两个参数放在一起'
.nargs=2
指定了 2 个参数,但并不使它们成为可选的(已经提出了一个 nargs=[0,2]
形式,但没有并入任何发行版).所以需要 --dates
使其成为可选的.为了产生这个帮助,元变量必须是一个元组(用列表试试看我的意思).而那个 tuple metavar
只适用于 optionals
(不是位置).
There isn't a way of specifying - 'require these 2 arguments together'
. nargs=2
specifies 2 arguments, but doesn't make them optional (a nargs=[0,2]
form has been proposed but not incorporated into any distribution). So --dates
is needed to make it optional. To produce this help, the metavar must be a tuple (try it with a list to see what I mean). And that tuple metavar
only works for optionals
(not positionals).
这篇关于Python 可选参数对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!