更新时间:2022-06-19 09:53:57
nargs='?'
在代码中手动检查未处于 list-methods 模式时是否已设置了纬度和经度
nargs='?'
for your positional argumentscheck manually in your code that both latitude and longitude have been set when you're not in list-methods mode
parser = argparse.ArgumentParser()
parser.add_argument('lat', help="latitude",default=None, nargs='?')
parser.add_argument('lon', help="longitude",default=None, nargs='?')
parser.add_argument('--method', help="calculation method (default: add)", default="add")
parser.add_argument('--list-methods', help="list available methods", action="store_true")
args = vars(parser.parse_args())
if not args['list_methods'] and (args['lat'] == None or args['lon'] == None):
print '%s: error: too few arguments' % sys.argv[0]
exit(0)
if args['list_methods']:
print 'list methods here'
else :
print 'normal script execution'
给出:
$ test.py --list-methods
在此处列出方法
$ test.py --list-methods
list methods here
$ test.py 4
test.py:错误:参数太少
$ test.py 4
test.py: error: too few arguments
test.py 4 5
正常脚本执行
test.py 4 5
normal script execution