Preserve case in ConfigParser?

前端 未结 5 1829
闹比i
闹比i 2020-12-04 23:00

I have tried to use Python\'s ConfigParser module to save settings. For my app it\'s important that I preserve the case of each name in my sections. The docs mention that pa

相关标签:
5条回答
  • 2020-12-04 23:30

    I know this question is answered, but I thought some people might find this solution useful. This is a class that can easily replace the existing ConfigParser class.

    Edited to incorporate @OozeMeister's suggestion:

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

    Usage is the same as normal ConfigParser.

    parser = CaseConfigParser()
    parser.read(something)
    

    This is so you avoid having to set optionxform every time you make a new ConfigParser, which is kind of tedious.

    0 讨论(0)
  • 2020-12-04 23:33

    Add to your code:

    config.optionxform = lambda option: option  # preserve case for letters
    
    0 讨论(0)
  • 2020-12-04 23:35

    For me worked to set optionxform immediately after creating the object

    config = ConfigParser.RawConfigParser()
    config.optionxform = str 
    
    0 讨论(0)
  • 2020-12-04 23:43

    The documentation is confusing. What they mean is this:

    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')
    

    I.e. override optionxform, instead of calling it; overriding can be done in a subclass or in the instance. When overriding, set it to a function (rather than the result of calling a function).

    I have now reported this as a bug, and it has since been fixed.

    0 讨论(0)
  • 2020-12-04 23:43

    Caveat:

    If you use defaults with ConfigParser, i.e.:

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

    and then try to make the parser case-sensitive by using this:

    config.optionxform = str
    

    all your options from config file(s) will keep their case, but FOO_BAZ will be converted to lowercase.

    To have defaults also keep their case, use subclassing like in @icedtrees answer:

    class CaseConfigParser(ConfigParser.SafeConfigParser):
        def optionxform(self, optionstr):
            return optionstr
    
    config = CaseConfigParser({'FOO_BAZ': 'bar'})
    

    Now FOO_BAZ will keep it's case and you won't have InterpolationMissingOptionError.

    0 讨论(0)
提交回复
热议问题