4

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

4

3 に答える 3

5

末尾の を取り除きたい場合は、atomocopter の提案に従って=サブクラス化し、独自のメソッドを実装して元のメソッドを置き換えることができます。ConfigParser.ConfigParserwrite

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し、各セクションのコメントを取得できるようにするメソッドを追加する必要があります。
于 2011-12-16T14:11:34.197 に答える
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
于 2011-12-16T12:58:05.623 に答える
0

末尾の「=」を回避するには、構成インスタンスをファイルに書き込んだ後、subprocess モジュールで sed コマンドを使用できます。

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

filepath は、ConfigParser を使用して生成した INI ファイルです。

于 2013-12-27T13:14:54.043 に答える