使用configparser添加注释

4 投票
3 回答
4329 浏览
提问于 2025-04-17 08:30

我可以在Python中使用ConfigParser模块来创建ini文件,方法是用add_section和set(可以参考这个链接 http://docs.python.org/library/configparser.html)。但是我没有看到关于添加注释的内容。这可能吗?我知道可以用#和;来添加注释,但我想知道怎么让ConfigParser对象帮我添加注释?在configparser的文档中没有看到相关的信息。

3 个回答

0

为了避免结尾出现“=”这个符号,你可以使用sed命令配合subprocess模块,前提是你已经把配置实例写入了一个文件。

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

这里的filepath就是你用ConfigParser生成的INI文件。

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
5

如果你想去掉结尾的 =,可以像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 方法,以便获取每个部分的注释。

撰写回答