python optparse how to set a args of list?

1.9k views Asked by At

I want to pass data to script, like this

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 are 'high', 'middle', 'low', 'all'")
    options, args = parser.parse_args()

in this script, if I want to set ./test.py -r high and middle, how can I set ['high', 'middle'] in optparse?

1

There are 1 answers

0
fferri On

https://docs.python.org/2/library/optparse.html#standard-option-types

"choice" options are a subtype of "string" options. The choices option attribute (a sequence of strings) defines the set of allowed option arguments. optparse.check_choice() compares user-supplied option arguments against this master list and raises OptionValueError if an invalid string is 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 are 'high', 'middle', 'low', 'all'")

If you want to be able to pass multiple values to --risk, you should use action="append":

An option’s action determines what optparse does when it encounters this option on the command-line. The standard option actions hard-coded into optparse are:

...

  • "append" [relevant: type, dest, nargs, choices]

    The option must be followed by an argument, which is appended to the list in dest. If no default value for dest is supplied, an empty list is automatically created when optparse first encounters this option on the command-line. If nargs > 1, multiple arguments are consumed, and a tuple of length nargs is appended to dest.

Also beware of combining action="append" with default=['high'], because you'll end up in always having 'high' in your 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 are 'high', 'middle', 'low'")

Usage:

>>> options, args = parser.parse_args(['-r','high','-r','medium'])
>>> options.risk
['high', 'medium']