使用configparser添加评论

时间:2011-12-16 11:54:27

标签: python configparser

我可以使用python中的ConfigParser模块使用add_section和set方法创建ini文件(参见http://docs.python.org/library/configparser.html中的示例)。但我没有看到任何关于添加评论的内容。那可能吗?我知道使用#和;但如何让ConfigParser对象为我添加?我在configparser的文档中没有看到任何相关内容。

3 个答案:

答案 0 :(得分:4)

如果你想摆脱尾随的=,你可以按照atomocopter的建议继承ConfigParser.ConfigParser并实现你自己的write方法来替换原来的方法:

import sys
import ConfigParser

class ConfigParserWithComments(ConfigParser.ConfigParser):
    def add_comment(self, section, comment):
        self.set(section, '; %s' % (comment,), None)

    def write(self, fp):
        """Write an .ini-format representation of the configuration state."""
        if self._defaults:
            fp.write("[%s]\n" % ConfigParser.DEFAULTSECT)
            for (key, value) in self._defaults.items():
                self._write_item(fp, key, value)
            fp.write("\n")
        for section in self._sections:
            fp.write("[%s]\n" % section)
            for (key, value) in self._sections[section].items():
                self._write_item(fp, key, value)
            fp.write("\n")

    def _write_item(self, fp, key, value):
        if key.startswith(';') and value is None:
            fp.write("%s\n" % (key,))
        else:
            fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))


config = ConfigParserWithComments()
config.add_section('Section')
config.set('Section', 'key', 'value')
config.add_comment('Section', 'this is the comment')
config.write(sys.stdout)

此脚本的输出为:

[Section]
key = value
; this is the comment

注意:

  • 如果您使用名称以;开头并且值设置为None的选项名称,则会将其视为评论。
  • 这将允许您添加注释并将其写入文件,但不会将其读回。为此,您将实现自己的_read方法,该方法负责解析注释,并可能添加comments方法,以便为每个部分获取注释。

答案 1 :(得分:1)

创建一个子类,或更简单:

import sys
import ConfigParser

ConfigParser.ConfigParser.add_comment = lambda self, section, option, value: self.set(section, '; '+option, value)

config = ConfigParser.ConfigParser()
config.add_section('Section')
config.set('Section', 'a', '2')
config.add_comment('Section', 'b', '9')
config.write(sys.stdout)

生成此输出:

[Section]
a = 2
; b = 9

答案 2 :(得分:0)

为了避免尾随“=”,一旦将配置实例写入文件,就可以将sed命令与子进程模块一起使用

<强> **subprocess.call(['sed','-in','s/\\(^#.*\\)=/\\n\\1/',filepath])**

filepath是您使用ConfigParser生成的INI文件