Adding a comment using configparser

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

+4
source share
3 answers

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

 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:

 [Section] key = value ; this is the comment 

Notes:

  • If you use the name of a parameter whose name begins with ; , and the value is None , this will be considered a comment.
  • This will allow you to add comments and write them to files, but not read them. To do this, you will implement your own _read method, which will take care of parsing comments and, possibly, add the comments method to get comments for each section.
+4
source

Make a subclass or simpler:

 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 conclusion:

 [Section] a = 2 ; b = 9 
+1
source

To avoid the final "=", you can use the sed command with the subprocess module as soon as you write the configuration instance to the file

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

filepath is an INI file generated using ConfigParser

0
source

Source: https://habr.com/ru/post/1386695/


All Articles