ConfigParserで大文字と小文字を保持しますか?
-
05-07-2019 - |
質問
Pythonの ConfigParser モジュールを使用して設定を保存しようとしました。私のアプリでは、各セクションの名前の大文字と小文字を保持することが重要です。ドキュメントでは、str()を ConfigParser.optionxform()これを達成できますが、私にはうまくいきません。名前はすべて小文字です。何か不足していますか?
<~/.myrc contents>
[rules]
Monkey = foo
Ferret = baz
取得したもののPython擬似コード:
import ConfigParser,os
def get_config():
config = ConfigParser.ConfigParser()
config.optionxform(str())
try:
config.read(os.path.expanduser('~/.myrc'))
return config
except Exception, e:
log.error(e)
c = get_config()
print c.options('rules')
[('monkey', 'foo'), ('ferret', 'baz')]
解決
ドキュメントはわかりにくいです。意味は次のとおりです:
import ConfigParser, os
def get_config():
config = ConfigParser.ConfigParser()
config.optionxform=str
try:
config.read(os.path.expanduser('~/.myrc'))
return config
except Exception, e:
log.error(e)
c = get_config()
print c.options('rules')
つまりoptionxformを呼び出す代わりにオーバーライドします。オーバーライドは、サブクラスまたはインスタンスで実行できます。オーバーライドするときは、(関数を呼び出した結果ではなく)関数に設定します。
これをバグとして報告しました。その後修正されました。
他のヒント
私にとっては、オブジェクトを作成した直後にoptionxformを設定するように働きました
config = ConfigParser.RawConfigParser()
config.optionxform = str
コードに追加:
config.optionxform = lambda option: option # preserve case for letters
この質問には答えられていることは知っていますが、このソリューションが役立つと考える人もいると思います。これは、既存のConfigParserクラスを簡単に置き換えることができるクラスです。
@OozeMeisterの提案を組み込むために編集:
class CaseConfigParser(ConfigParser):
def optionxform(self, optionstr):
return optionstr
使用法は通常のConfigParserと同じです。
parser = CaseConfigParser()
parser.read(something)
これにより、新しい ConfigParser
を作成するたびにoptionxformを設定する必要がなくなります。これは面倒です。
注意:
ConfigParserでデフォルトを使用する場合、つまり:
config = ConfigParser.SafeConfigParser({'FOO_BAZ': 'bar'})
次に、これを使用してパーサーの大文字と小文字を区別しようとします:
config.optionxform = str
設定ファイルのすべてのオプションでは大文字と小文字が区別されますが、 FOO_BAZ
は小文字に変換されます。
デフォルトでも大文字と小文字を区別するには、@ icedtrees answerのようなサブクラスを使用します。
class CaseConfigParser(ConfigParser.SafeConfigParser):
def optionxform(self, optionstr):
return optionstr
config = CaseConfigParser({'FOO_BAZ': 'bar'})
Now FOO_BAZ
は大文字小文字を保持し、 InterpolationMissingOptionError は発生しません。