107

我尝试使用 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')]
4

5 回答 5

129

文档令人困惑。他们的意思是:

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,而不是调用它;覆盖可以在子类或实例中完成。覆盖时,将其设置为函数(而不是调用函数的结果)。

我现在将此报告为一个错误,并且已得到修复。

于 2009-10-23T07:33:21.463 回答
53

对我来说,optionxform在创建对象后立即设置

config = ConfigParser.RawConfigParser()
config.optionxform = str
于 2014-05-23T19:02:38.770 回答
12

添加到您的代码中:

config.optionxform = lambda option: option  # preserve case for letters
于 2018-08-19T04:09:10.043 回答
6

我知道这个问题已经得到解答,但我认为有些人可能会发现这个解决方案很有用。这是一个可以轻松替换现有类的ConfigParser类。

编辑以合并@OozeMeister 的建议:

class CaseConfigParser(ConfigParser):
    def optionxform(self, optionstr):
        return optionstr

用法同普通ConfigParser

parser = CaseConfigParser()
parser.read(something)

这样可以避免optionxform每次制作新的时都必须设置ConfigParser,这有点乏味。

于 2014-04-11T08:53:15.223 回答
4

警告:

如果您使用 ConfigParser 的默认值,即:

config = ConfigParser.SafeConfigParser({'FOO_BAZ': 'bar'})

然后尝试使用以下方法使解析器区分大小写:

config.optionxform = str

配置文件中的所有选项都将保留它们的大小写,但FOO_BAZ将转换为小写。

要让默认值也保留它们的大小写,请使用@icedtrees 答案中的子类化:

class CaseConfigParser(ConfigParser.SafeConfigParser):
    def optionxform(self, optionstr):
        return optionstr

config = CaseConfigParser({'FOO_BAZ': 'bar'})

现在FOO_BAZ将保持这种情况,您将不会有InterpolationMissingOptionError

于 2017-02-23T05:11:58.367 回答