Adding comment with configparser

大城市里の小女人 提交于 2019-12-07 11:19:27

问题


I can use the ConfigParser module in python to create ini-files using the methods add_section and set (see sample in http://docs.python.org/library/configparser.html). But I don't see anything about adding comments. Is that possible? I know about using # and ; but how to get the ConfigParser object to add that for me? I don't see anything about this in the docs for configparser.


回答1:


If you want to get rid of the trailing =, you can subclass ConfigParser.ConfigParser as suggested by atomocopter and implement your own write method to replace the original one:

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)

The output of this script is:

[Section]
key = value
; this is the comment

Notes:

  • If you use an option name whose name starts with ; and value is set to None, it will be considered a comment.
  • This will let you add comments and write them to files, but not read them back. To do that, you'll have implement your own _read method that takes care of parsing comments and maybe add a comments method to make it possible to get the comments for each section.



回答2:


Make a subclass, or easier:

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)

Produces this output:

[Section]
a = 2
; b = 9



回答3:


To avoid the trailing "=" you can use the sed command with subprocess module, once you have written the config instance to a file

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

filepath is the INI file you generated using the ConfigParser



来源:https://stackoverflow.com/questions/8533797/adding-comment-with-configparser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!