我有一个opts解析。 例如:
from optparse import OptionParser
parser = OptionParser()
parser.add_option("ablah, dest = 'a',\
action = 'store', nargs=2)
parser.add_option("bblah, dest = 'b',\
action = 'store', nargs=2)
parser.add_option("cblah, dest = 'c',\
action = 'store', nargs=2)
现在我会得到一本字典。这个问题是opts的一个属性。 所以我试过了:
for x in opts.__dict__.iterkeys():
if x = 'bblah':
callfunction1(opts.bblah[0],opts.bblah[1])
if x = 'ablah':
callfunction2(opts.ablah[0],opts.ablah[1])
if x = 'cblah':
callfunction3(opts.cblah[0],opts.cblah[1])
这里的问题是2折。
我知道有人说这种方法通常是飞跃,而不是要求原谅,但我想先做检查。
感谢。
答案 0 :(得分:0)
我不确定我是否理解你的问题,但也许这可以给你一个提示:
# map option name to function
func_map = {'ablah': ablah,
'bblah': bblah,
'cblah': cblah}
# filter out the options without argument
# this may be redundant, optparse can make proper validations
selected = filter(lambda x: x[1], opts.__dict__.items())
for k, v in selected:
func_map[k](*v)