python optparse如何设置列表的args?

时间:2015-06-26 09:13:09

标签: python optparse

我想将数据传递给脚本,就像这样

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

在这个脚本中,如果我想设置./test.py -r高和中,我怎样才能在['high', 'middle']中设置optparse

1 个答案:

答案 0 :(得分:1)

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']