python中可选参数是什么意思,Python可选参数对

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')

which gives

> python test_arg.py -h

usage: test_arg.py [-h] [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]

Is it possible with 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())

which produces

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

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).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值