我尝试使用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的子类:

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

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

现在 FOO_BAZ 将保持原样,你不会有 InterpolationMissingOptionError

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top