简体   繁体   中英

Python - ConfigParser throwing comments

Based on ConfigParser module how can I filter out and throw every comments from an ini file?

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)

eg. in the ini file below the above basic script prints out the further comments lines as well like:

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

What I need is having only the section names and pure key-value pairs inside them without any comments. Does ConfigParser handles this somehow or should I use regexp...or? Cheers

according to docs lines starting with ; or # will be ignored. it doesn't seem like your format satisfies that requirement. can you by any chance change format of your input file?

edit : since you cannot modify your input files, I'd suggest pre-parsing them with something along the lines:

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

obviously if semi-colon is present in options you'll have to be more creative.

Best way is to write a commentless file subclass:

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

You could use it then with configparser (your code):

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)

It seems your comments are not on lines that start with the comment leader. It should work if the comment leader is the first character on the line.

As the doc said: "(For backwards compatibility, only ; starts an inline comment, while # does not.)" So use ";" and not "#" for inline comments. It is working well for me.

Python 3 comes with a build-in solution: The class configparser.RawConfigParser has constructor argument inline_comment_prefixes . Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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