繁体   English   中英

Python-ConfigParser引发注释

[英]Python - ConfigParser throwing comments

基于ConfigParser模块,如何从ini文件中过滤掉并抛出所有注释?

import ConfigParser
config = ConfigParser.ConfigParser()
config.read("sample.cfg")

for section in config.sections():
    print section
    for option in config.options(section):
        print option, "=", config.get(section, option)

例如。 在上述基本脚本下面的ini文件中,还打印了更多注释行,例如:

something  = 128     ; comment line1
                      ; further comments 
                       ; one more line comment

我需要的是其中仅包含节名称和纯键值对,而没有任何注释。 ConfigParser是否以某种方式处理此问题,还是应该使用regexp ...还是? 干杯

根据docs开头的一行; #将被忽略。 您的格式似乎不满足该要求。 您是否可以随意更改输入文件的格式?

编辑 :由于您不能修改您的输入文件,我建议使用以下内容预先准备它们:

tmp_fname = 'config.tmp'
with open(config_file) as old_file:
    with open(tmp_fname, 'w') as tmp_file:
        tmp_file.writelines(i.replace(';', '\n;') for i in old_lines.readlines())
# then use tmp_fname with ConfigParser

显然,如果选项中包含分号,则您必须更具创造力。

最好的方法是编写一个无注释的file子类:

class CommentlessFile(file):
    def readline(self):
        line = super(CommentlessFile, self).readline()
        if line:
            line = line.split(';', 1)[0].strip()
            return line + '\n'
        else:
            return ''

然后可以将其与c​​onfigparser(您的代码)一起使用:

import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(CommentlessFile("sample.cfg"))

for section in config.sections():
    print section
    for option in config.options(section):
        print option, "=", config.get(section, option)

您的评论似乎不在以评论领导者开头的行上。 如果注释领导者是该行的第一个字符,它应该可以工作。

正如文档所说:“(为了向后兼容,仅;开始内联注释,而#则不行。)”因此,请使用“;” 而不是内嵌注释的“#”。 对我来说很好。

Python 3带有一个内置解决方案: configparser.RawConfigParser类具有构造函数参数inline_comment_prefixes 例:

class MyConfigParser(configparser.RawConfigParser):
    def __init__(self):
      configparser.RawConfigParser.__init__(self, inline_comment_prefixes=('#', ';'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM