一种可选的参数,不需要位置参数 [英] One optional argument which does not require positional arguments
问题描述
我对python的argparse有疑问:是否可以有一个不需要位置参数的可选参数?
I have a question regarding python's argparse: Is it possible to have a optional argument, which does not require positional arguments?
示例:
parser.add_argument('lat', help="latitude")
parser.add_argument('lon', help="longitude")
parser.add_argument('--method', help="calculation method (default: add)", default="add")
parser.add_argument('--list-methods', help="list available methods", action="store_true")
正常命令行为test.py 47.249 -33.282
或test.py 47.249 -33.282 --method sub
.但是,一旦我用test.py --list-methods
调用脚本以列出所有可用的方法,我就会得到error: to few arguments
.如何使用argparse来具有此可选参数(--list-methods)而没有位置参数(lat,lon)?
The normal command line would be test.py 47.249 -33.282
or test.py 47.249 -33.282 --method sub
. But as soon as I call the script with test.py --list-methods
to list all available methods, I get error: to few arguments
. How can I use argparse to have this optional argument (--list-methods) without having positional arguments (lat, lon)?
推荐答案
- 设置默认值,并为位置参数设置
nargs='?'
-
在代码中手动检查未处于 list-methods 模式时是否已设置了纬度和经度
- set a default value and
nargs='?'
for your positional arguments check 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 argumentstest.py 4 5
正常脚本执行test.py 4 5
normal script execution这篇关于一种可选的参数,不需要位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- set a default value and