保留ConfigParser中的案例?

poj*_*ojo 77 python configuration-files python-2.x configparser

我曾尝试使用Python的ConfigParser模块来保存设置.对于我的应用程序,重要的是我在我的部分中保留每个名称的大小写.文档提到将str()传递给ConfigParser.optionxform()会实现这一点,但它对我不起作用.名称都是小写的.我错过了什么吗?

<~/.myrc contents>
[rules]
Monkey = foo
Ferret = baz
Run Code Online (Sandbox Code Playgroud)

我获得的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')]
Run Code Online (Sandbox Code Playgroud)

Mar*_*wis 99

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

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')
Run Code Online (Sandbox Code Playgroud)

即覆盖optionxform,而不是调用它; 覆盖可以在子类或实例中完成.覆盖时,将其设置为函数(而不是调用函数的结果).

我现在已将此报告为一个错误,并且已经修复.


uli*_*der 27

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

config = ConfigParser.RawConfigParser()
config.optionxform = str 
Run Code Online (Sandbox Code Playgroud)

  • 请注意,它也适用于`ConfigParser.ConfigParser()` (3认同)
  • 效果很好!(请注意,在python 3中它是“configparser”类名(无大写) (2认同)
  • @NoamManos:您指的是模块名称(类名称仍然是 [ConfigParser](https://docs.python.org/3/library/configparser.html#configparser.ConfigParser))。 (2认同)

ice*_*ees 6

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

编辑以纳入@OozeMeister 的建议:

class CaseConfigParser(ConfigParser):
    def optionxform(self, optionstr):
        return optionstr
Run Code Online (Sandbox Code Playgroud)

用法和正常一样ConfigParser

parser = CaseConfigParser()
parser.read(something)
Run Code Online (Sandbox Code Playgroud)

这样你就可以避免optionxform每次创建 new 时都必须设置ConfigParser,这有点乏味。


Foo*_*167 5

添加到您的代码:

config.optionxform = lambda option: option  # preserve case for letters
Run Code Online (Sandbox Code Playgroud)

  • 这与得分最高的答案相同 - 请参阅行 `config.optionxform=str` :) 只是代替您的 lamdba @Martin v. Löwis 使用嵌入式 `str` 函数 (2认同)