Python OptsParse属性检查..我想

时间:2011-10-15 22:05:08

标签: python parsing dictionary arguments

我有一个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折。

  1. 我在opts元组/字典中有多个元素。
  2. 我如何检查以确保这些对象具有值。否则我得到你不能用None调用值。我需要在这里完成“检查”,因为如果我在函数中执行它会导致一些严重的错误
  3. 我知道有人说这种方法通常是飞跃,而不是要求原谅,但我想先做检查。

    感谢。

1 个答案:

答案 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)