我有下面的python代码,应检查cfg中参数的值是否具有可在字典dict_methos_modes中找到的正确值,请参阅下文:
因此,如果tmp_method是粗略的'那么参数模式(来自cfg文件)应该只有一个值:' per_node',' master_only',' slave_only',' master_slave& #39 ;.如果参数模式具有不同的值,则代码应删除该选项,并在下一步中添加默认值!
listSectionsInCfg = ['Settings', 'Run']
listSettingsParameters = ['method', 'mode']
listExecutionParameters = ['test']
dict_methods_modes = {
'rough':['per_node', 'master_only', 'slave_only', 'master_slave'],
'medium':['replica', 'master', 'slave']}
cfg = ConfigParser.SafeConfigParser()
cfg.optionxform = str
cfg.read(file)
try:
for section in listSectionsCfg:
print 'Now reading %s'%(section)
assert cfg.has_section(section)
if section == 'Settings': listCandidate = listSettingsParameters
if section == 'Run': listCandidate = listExecutionParameters
for candidate in listCandidate:
if 'method' == candidate:
if cfg.has_option(section, candidate):
tmp_method = cfg.get(section, candidate)
if all(x != tmp_method for x in dict_methods_modes):
print '%s.%-12s : %s -> wrong syntax, cleared'%(section, candidate, tmp_method)
cfg.remove_option(section, candidate)
elif 'mode' == candidate:
tmp_method = cfg.get(section, 'method')
if cfg.has_option(section, candidate):
tmp_mode = cfg.get(section, candidate)
print 'TEST-POINT:%s.%-12s : %s'%(section, candidate, tmp_mode)
ll = [v for v in dict_methods_modes[tmp_method] if v == tmp_mode]
print 'TEST-POINT:%s'%(ll)
if not ll:
print '%s.%-12s : %s -> wrong syntax, cleared'%(section, candidate, tmp_mode)
cfg.remove_option(section, candidate)
# Check if candidate exists
if cfg.has_option(section, candidate):
continue
else: # if not set default values for candidate
print '%s.%-12s : %s -> missing'%(section, candidate, cfg.has_option(section, candidate))
if 'method' == candidate:
cfg.set(section, candidate, 'rough')
print '%s.%-12s : %s'%(section, candidate, cfg.get(section, candidate))
elif 'mode' == candidate:
cfg.set(section, candidate, 'per_node')
print '%s.%-12s : %s'%(section, candidate, cfg.get(section, candidate))
如果我执行上面的代码,我得到以下打印输出,cfg文件中的参数模式设置为' blabla',
cfg文件:
[Settings]
method = rough
mode = blabla
[Run]
test = once
但我得到了:
TEST-POINT:Settings.mode : per_node
TEST-POINT:['per_node']
由于ll不为空,因此不会删除mode参数以获取下一步的默认值!
另一件事是,如果我注释掉用于检查列表的if语句ll empty:
#if not ll:
# print '%s.%-12s : %s -> wrong syntax, cleared'%(section, candidate, tmp_mode)
# cfg.remove_option(section, candidate)
在这种情况下的打印输出是:
TEST-POINT:Settings.mode : blabla
TEST-POINT:[]
哪个是正确的,但代码无法删除模式参数! 我的代码中我做错了什么?