python optparse how to set a args of list? -
i want pass data script,
if __name__ == '__main__': usage = 'python pull.py [-h <host>][-p <port>][-r <risk>]arg1[,arg2..]' parser = optionparser(usage) parser.add_option('-o', '--host', dest='host', default='127.0.0.1', ┊ help='mongodb host') parser.add_option('-p', '--port', dest='port', default=27017, ┊ help="mongodb port") parser.add_option('-r', "--risk", dest='risk', default="high", ┊ help="the risk of site, choice 'high', 'middle', 'low', 'all'") options, args = parser.parse_args()
in script, if want set ./test.py -r high , middle, how can set ['high', 'middle']
in optparse
?
https://docs.python.org/2/library/optparse.html#standard-option-types
"choice"
options subtype of "string" options. choices option attribute (a sequence of strings) defines set of allowed option arguments.optparse.check_choice()
compares user-supplied option arguments against master list , raisesoptionvalueerror
if invalid string given.
e.g:
parser.add_option('-r', '--risk', dest='risk', default='high', type='choice', choices=('high', 'medium', 'low', 'all'), help="the risk of site, choice 'high', 'middle', 'low', 'all'")
if want able pass multiple values --risk
, should use action="append"
:
an option’s
action
determines optparse when encounters option on command-line. standard option actions hard-coded optparse are:...
"append"
[relevant:type
,dest
,nargs
,choices
]the option must followed argument, appended list in
dest
. if no default valuedest
supplied, empty list automatically created when optparse first encounters option on command-line. ifnargs
> 1, multiple arguments consumed, , tuple of lengthnargs
appendeddest
.
also beware of combining action="append"
default=['high']
, because you'll end in having 'high' in options.risk
.
parser.add_option('-r', '--risk', dest='risk', default=[], nargs=1, type='choice', choices=('high', 'medium', 'low'), action='append', help="the risk of site, choice 'high', 'middle', 'low'")
usage:
>>> options, args = parser.parse_args(['-r','high','-r','medium']) >>> options.risk ['high', 'medium']
Comments
Post a Comment