gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:17:20 29 4
gpt4 key购买 nike

下面是我的示例配置文件

[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 个循环进行迭代。

最佳答案

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

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 中覆盖 RawConfigParser 子类中的 _read 并在 Python 中使用自定义可变映射类型作为 dict_type > = 2.6,优点是在解析配置时已经执行了检查;无需再次迭代完全解析的配置。

关于Python ConfigParser 检查选项是否为空的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54901114/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com