代码之家  ›  专栏  ›  技术社区  ›  pojo

在ConfigParser中保留案例?

  •  62
  • pojo  · 技术社区  · 15 年前

    我试过用蟒蛇的 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')]
    
    5 回复  |  直到 6 年前
        1
  •  86
  •   tshepang Arrie    11 年前

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

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

    我现在已经报告了 this as a bug ,它已经被修复了。

        2
  •  23
  •   ulitosCoder    10 年前

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

    config = ConfigParser.RawConfigParser()
    config.optionxform = str 
    
        3
  •  3
  •   icedtrees    9 年前

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

    编辑以纳入@oozemeister的建议:

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

    用法与普通配置程序相同。

    parser = CaseConfigParser()
    parser.read(something)
    

    这是为了避免每次创建新的 ConfigParser 有点乏味。

        4
  •  3
  •   FooBar167    6 年前

    添加到代码:

    config.optionxform = lambda option: option  # preserve case for letters
    
        5
  •  2
  •   nidalpres    8 年前

    Caveat:

    如果将默认值与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'})
    

    现在 福伊巴兹 会保持现状,而你不会 插值误差 .