2011-10-15 26 views
0

我有一個opts解析。 例:Python OptsParse屬性檢查..我認爲

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調用值。我需要這個「檢查」在這裏完成,因爲它會導致一些嚴重的錯誤,如果我這樣做的功能

我知道有人說這種方法通常是飛躍而不是要求原諒,但我想先做檢查。

謝謝。

回答

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)