Python ConfigParser检查选项是否为空的有效方法

问题描述 投票:1回答:1

下面是我的示例配置文件

[HEAD1]
key1 = val1
key2 = val2

[HEAD2]
key1 = 
key2 = val2

我想编写一个有效的代码,它会向用户抛出一个错误,指示任何选项是否缺少值(如果它是空的而不是'='后给定的值)

我正在使用Python ConfigParser模块

import ConfigParser
config = ConfigParser.RawConfigParser()
config.read("./mytest.cfg")
for section in config.sections():
    for option in config.options(section):
        if not config.get(section, option):
           print "Option: %s has no value under section %s" %(option,section)

我很高兴知道是否有任何有效的方法来快速识别相同而不是迭代2循环。

python configparser
1个回答
0
投票

从解析器的角度来看,key1部分中的选项HEAD2确实有一个值;空字符串实例,它构成解析器的有效值:

print repr(config.get('HEAD2', 'key1'))
# Output: ''

您可以继承RawConfigParser并覆盖_read()方法,以便在它们被插入内部字典之前捕获这些空字符串值。然而,_read是相当冗长的,并在那里捕获不需要的值似乎有点笨拙。如果我的Python版本低于2.6,我只会走这条路。 在这种情况下,您将在处理选项行时添加对空字符串的检查

if optval == '':
    print "Option: %s has no value under section %s" % (optname, cursect['__name__'])

empty values have been handled之后。


从Python 2.6开始,RawConfigParser(及其后代)采用可选参数dict_type,它允许您传入解析器将在内部使用的自定义字典类。 从Python 2.7开始,默认值为collections.OrderedDict,后退内置dict。 您可以创建一个自定义dict类,以警告空字符串实例作为值:

# as done in ConfigParser
try:
    from collections import OrderedDict as _default_dict
except ImportError:
    # fallback for setup.py which hasn't yet built _collections
    _default_dict = dict


class NotifyEmptyStringValueDict(_default_dict):

    def __setitem__(self, key, value):
        if value == "":
            # Consider raising an exception here instead, e.g. ValueError,
            # unless you don't want empty string values to break the parsing
            # and just want a warning message to be displayed while parsing continues
            print "Option: %s has no value under section %s" % (key, self['__name__'])
            # accessing self['__name__'] obviously raises a KeyError when used
            # outside the context of a parser instance. In a parser, this holds
            # the section name
        _default_dict.__setitem__(self, key, value)

然后使用此类将解析器实例化为dict_type

config = ConfigParser.RawConfigParser(dict_type=NotifyEmptyStringValueDict)
config.read("./mytest.cfg")

这两个选项,在Python <2.6中的_read的子类中覆盖RawConfigParser,并在Python> = 2.6中使用自定义可变映射类型作为dict_type,具有在解析配置时已执行检查的优点;无需再次遍历完全解析的配置。

© www.soinside.com 2019 - 2024. All rights reserved.