Python可选参数对 [英] Python Optional Argument Pair

查看:70
本文介绍了Python可选参数对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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 DATEEND 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

无法指定-'require these 2 arguments together'. nargs=2指定2个参数,但不使其成为可选参数(已提出nargs=[0,2]形式,但未将其包含在任何发行版中).因此,需要--dates使其成为可选.要提供此帮助,metavar必须是一个元组(尝试使用列表来了解我的意思).而且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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆