Python Config解析器如何读取带注释的值
我有一个配置文件,
[local]
variable1 : val1 ;#comment1
variable2 : val2 ;#comment2
像这样的代码只读取键的值:
class Config(object):
def __init__(self):
self.config = ConfigParser.ConfigParser()
self.config.read('config.py')
def get_path(self):
return self.config.get('local', 'variable1')
if __name__ == '__main__':
c = Config()
print c.get_path()
但是我还想读取与值一起存在的注释,关于这方面的任何建议都将非常有帮助。
5 个回答
根据ConfigParser模块的说明,
配置文件可以包含注释,这些注释以特定字符(#和;)开头。注释可以单独出现在空行中,也可以出现在包含值或章节名称的行中。在后者的情况下,注释前需要有一个空格字符才能被识别为注释。(为了向后兼容,只有;可以在行内开始注释,而#则不可以。)
如果你想把“注释”当作值来读取,可以在;
字符前面不加空格,或者使用#
。但这样的话,comment1
和comment2
就会变成值的一部分,不再被视为注释。
一个更好的方法是使用不同的属性名称,比如variable1_comment
,或者在配置中定义一个专门用于注释的章节:
[local]
variable1 = value1
[comments]
variable1 = comment1
第一个解决方案需要你用另一个键生成一个新键(也就是说,从variable1
计算出variable1_comment
),而另一个方案则允许你在配置文件中使用相同的键来指向不同的章节。
从Python 2.7.2开始,如果你使用#
字符,总是可以在行中读取注释。正如文档所说,这是为了向后兼容。以下代码应该可以顺利运行:
config = ConfigParser.ConfigParser()
config.read('config.ini')
assert config.get('local', 'variable1') == 'value1'
assert config.get('local', 'variable2') == 'value2 # comment2'
对于以下的config.ini
文件:
[local]
variable1 = value1 ; comment1
variable2 = value2 # comment2
如果你采用这个解决方案,记得手动解析get()
的结果,以获取值和注释。
唉,这个问题在一般情况下不容易解决。注释本来是应该被解析器忽略的。
不过在你的具体情况下,这个问题就简单多了,因为只有当#
在行首时,它才会被当作注释符号。所以变量variable1的值会是"val1 #comment1"
。我想你可能用的是类似的方式,只是更不容易出错:
val1_line = c.get('local', 'var1')
val1, comment = val1_line.split(' #')
如果你需要一个“注释”的值,那可能它就不算真正的注释了?可以考虑为“注释”添加明确的键,比如这样:
[local]
var1: 108.5j
var1_comment: remember, the flux capacitor capacitance is imaginary!
你唯一的解决办法就是写一个新的 ConfigParser
,并重写它的 _read()
方法。在你的 ConfigParser
中,你需要删除所有关于注释删除的检查。这是一个危险的解决方案,但应该能奏效。
class ValuesWithCommentsConfigParser(ConfigParser.ConfigParser):
def _read(self, fp, fpname):
from ConfigParser import DEFAULTSECT, MissingSectionHeaderError, ParsingError
cursect = None # None, or a dictionary
optname = None
lineno = 0
e = None # None, or an exception
while True:
line = fp.readline()
if not line:
break
lineno = lineno + 1
# comment or blank line?
if line.strip() == '' or line[0] in '#;':
continue
if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
# no leading whitespace
continue
# continuation line?
if line[0].isspace() and cursect is not None and optname:
value = line.strip()
if value:
cursect[optname].append(value)
# a section header or option header?
else:
# is it a section header?
mo = self.SECTCRE.match(line)
if mo:
sectname = mo.group('header')
if sectname in self._sections:
cursect = self._sections[sectname]
elif sectname == DEFAULTSECT:
cursect = self._defaults
else:
cursect = self._dict()
cursect['__name__'] = sectname
self._sections[sectname] = cursect
# So sections can't start with a continuation line
optname = None
# no section header in the file?
elif cursect is None:
raise MissingSectionHeaderError(fpname, lineno, line)
# an option line?
else:
mo = self._optcre.match(line)
if mo:
optname, vi, optval = mo.group('option', 'vi', 'value')
optname = self.optionxform(optname.rstrip())
# This check is fine because the OPTCRE cannot
# match if it would set optval to None
if optval is not None:
optval = optval.strip()
# allow empty values
if optval == '""':
optval = ''
cursect[optname] = [optval]
else:
# valueless option handling
cursect[optname] = optval
else:
# a non-fatal parsing error occurred. set up the
# exception but keep going. the exception will be
# raised at the end of the file and will contain a
# list of all bogus lines
if not e:
e = ParsingError(fpname)
e.append(lineno, repr(line))
# if any parsing errors occurred, raise an exception
if e:
raise e
# join the multi-line values collected while reading
all_sections = [self._defaults]
all_sections.extend(self._sections.values())
for options in all_sections:
for name, val in options.items():
if isinstance(val, list):
options[name] = '\n'.join(val)
在 ValuesWithCommentsConfigParser
中,我修复了一些导入的内容,并删除了相关的代码部分。
使用我之前回答中提到的同一个 config.ini
文件,我可以证明之前的代码是正确的。
config = ValuesWithCommentsConfigParser()
config.read('config.ini')
assert config.get('local', 'variable1') == 'value1 ; comment1'
assert config.get('local', 'variable2') == 'value2 # comment2'