2011-12-16 318 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生成