gpt4 book ai didi

python optparse 如何设置列表的参数?

转载 作者:太空宇宙 更新时间:2023-11-03 17:37:04 30 4
gpt4 key购买 nike

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

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

最佳答案

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.

例如:

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'")

如果您希望能够将多个值传递给 --risk ,你应该使用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.

还要注意组合 action="append"default=['high'] ,因为你最终会在 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'")

用法:

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

关于python optparse 如何设置列表的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31069279/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com