2011-12-16 3 views
3

pythonでConfigParserモジュールを使用して、add_sectionメソッドとsetメソッド(http://docs.python.org/library/configparser.htmlのサンプルを参照)を使用してiniファイルを作成できます。しかし、私はコメントを追加することについて何も表示されません。それは可能ですか?私は#と#を使うことを知っている。私のためにConfigParserオブジェクトを追加する方法は?私はconfigparserのためのドキュメントではこれについて何も表示されません。configparserでコメントを追加する

+3

[Python ConfigParserのファイルへのコメントの書き込みに関する質問](http://stackoverflow.com/questions/6620637/python-configparser-question-about-writing-comments-to) -fil es) – Chris

+0

ああ。私はその答えを見なかった。ごめんなさい!それは美しい解決策ではありませんが、私はそれをやらなければならないと思います。ありがとう! –

+0

はい、末尾の '= '記号については残念ですが、それについて多くのことはできません。 – Chris

答えて

4

あなたは末尾=を取り除きたい場合は、あなたが示唆したように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メソッドを追加する必要があります。
+0

それは素晴らしいですね。私は時間がかかるときにそれを調べます... –

+0

それは素晴らしい作品です。どうもありがとう。しかし、私は書き込みメソッドが何を得るのか分からない。私はそれを必要としませんか、何かが欠けていますか? –

+0

'write'メソッドは、あなたが設定ファイルに書き込むのに使うものです。デフォルト実装を使用しないようにする必要があります。 – jcollado

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 
+0

解決に感謝します。私はもちろんあなたが言ったことをすることができます(add_commentメソッドの+1)。しかし、それは醜い末尾の問題を解決するwould'nt = –

0

末尾を避けるために「=」あなたは、あなたがファイルに設定インスタンスを書いたら

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

ファイルパスを使用すると、INIファイルで、サブプロセスモジュールとのsedコマンドを使用することができますConfigParserを使用して生成される

関連する問題