【问题标题】:Python OptsParse Attribute Checking.. i thinkPython OptsParse 属性检查.. 我认为
【发布时间】:2011-12-08 12:28:09
【问题描述】:

我有一个 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 调用值。我需要在这里完成这个“检查”,因为如果我在函数中这样做会导致一些严重的错误

我知道有人说这种方法通常是跳跃而不是请求原谅,但我想先检查一下。

谢谢。

【问题讨论】:

    标签: python parsing dictionary arguments


    【解决方案1】:

    我不确定我是否正确理解了您的问题,但也许这可以给您一个提示:

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

    【讨论】:

      猜你喜欢
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 2015-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多