Python Optional Argument Pair

╄→гoц情女王★ 提交于 2020-01-13 09:02:53

问题


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?


回答1:


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




回答2:


I think the only way to do this is to do the check yourself:

if (not parser.start_date) != (not parser.end_date):
    print("Error: --start_date and --end_date must be used together.")
    arg_parser.print_usage()
    sys.exit(-1)

Unfortunately, that's not reflected in the help message.




回答3:


Try to add default=None as variable

parser.add_argument('start_date', nargs='?', metavar='START DATE',
                   help='start date in YYYY-MM-DD', default=None)
parser.add_argument('end_date', nargs='?', metavar='END DATE',
                   help='end date in YYYY-MM-DD', default=None)

I think that should work.



来源:https://stackoverflow.com/questions/19805170/python-optional-argument-pair

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!