忽略配置文件解析器中不存在的属性 python

Ignore non existing attributes in config file parser python

我有一个函数一次返回 1 个列表,如下所示

['7:49', 'Section1', '181', '1578', '634', '4055']
['7:49', 'Section2', '181', '1578', '634', '4055']

这些值是 time,section,count,avg,min,max(我知道这将永远是顺序) 我的目标是在任何值违反配置文件中定义的限制时发出警报。

所以我创建了如下配置

[Section1]
Count:10
Min:20
Max:100
Avg:50
[Section2]
Count:10
Min:20
Max:100
Avg:50

我检查最大和最小限制的函数

def checklimit(line):
    print "Inside CheckLimit", line[1],line[4],line[5]
    if line[4] < ConfigSectionMap(line[1])['min'] or line[5] > ConfigSectionMap(line[1])['max']:
        sendAlert(line)

这工作正常,但可以改进并且有一些特殊情况。 假设有人离开配置如下

[Section1]
Count:10
Min:
Max:
Avg:50
[Section2]
Count:10
Avg:50

意味着用户只想检查计数和平均值。应该如何在我的代码中处理这些情况,以便仅检查配置文件中给出的必需参数。我使用了来自 here

的 Config Parser

欢迎提出改进问题标题的建议。很难放一个。谢谢

有很多方法可以解决这个问题。通过键查找,您可以在字典中使用 dict.get() 方法并提供后备值。

所以而不是

ConfigSectionMap(line[1])['min']

你可以使用类似这样的东西,如果密钥不存在,它将 return 0

ConfigSectionMap(line[1]).get('min', 0)