ava*_*sal 8 python configparser
我有配置文件,
[local]
variable1 : val1 ;#comment1
variable2 : val2 ;#comment2
Run Code Online (Sandbox Code Playgroud)
像这样的代码只读取键的值:
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()
Run Code Online (Sandbox Code Playgroud)
但我也想阅读评论以及价值,这方面的任何建议都会非常有帮助.
唉,一般情况下这不容易做到.解析器应该忽略注释.
在您的特定情况下,它很容易,因为#如果它开始一行,它只用作注释字符.所以variable1的值将是"val1 #comment1".我想你使用这样的东西,只是不那么脆弱:
val1_line = c.get('local', 'var1')
val1, comment = val1_line.split(' #')
Run Code Online (Sandbox Code Playgroud)
如果需要'评论'的值,可能它不是一个正确的评论?考虑为"评论"添加显式键,如下所示:
[local]
var1: 108.5j
var1_comment: remember, the flux capacitor capacitance is imaginary!
Run Code Online (Sandbox Code Playgroud)
您唯一的解决方案是编写另一个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)
Run Code Online (Sandbox Code Playgroud)
在ValuesWithCommentsConfigParser我修复了一些导入并删除了适当的代码部分。
使用config.ini与我之前的答案相同的内容,我可以证明之前的代码是正确的。
config = ValuesWithCommentsConfigParser()
config.read('config.ini')
assert config.get('local', 'variable1') == 'value1 ; comment1'
assert config.get('local', 'variable2') == 'value2 # comment2'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4590 次 |
| 最近记录: |