2011-12-16 315 views
3

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

+3

请参阅接受的问题的答案[Python ConfigParser关于将注释写入文件](http://stackoverflow.com/questions/6620637/python-configparser-question-about-writing-comments-to -fil es) – Chris 2011-12-16 12:24:01

+0

哦。我没有看到答案。抱歉!这不是一个美丽的解决方案,但我想这是我必须这样做的方式。谢谢! – 2011-12-16 12:30:03

+0

是的,这对于后面的`=`符号是一种遗憾,但似乎并没有太多可以做的事情! – Chris 2011-12-16 12:33:45

回答

4

如果你想摆脱尾随=的,你也可以继承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

做一个子类,或更容易:

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) 

产生这样的输出:通过atomocopter

[Section] 
a = 2 
; b = 9 
0

为了避免尾随“=”您可以使用sed命令与子模块,一旦你写的配置实例文件

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

filepath是INI文件,你使用ConfigParser生成