Lists in ConfigParser

后端 未结 15 2021
清酒与你
清酒与你 2020-11-27 09:38

The typical ConfigParser generated file looks like:

[Section]
bar=foo
[Section 2]
bar2= baz

Now, is there a way to index lists like, for in

15条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 10:12

    import ConfigParser
    import os
    
    class Parser(object):
        """attributes may need additional manipulation"""
        def __init__(self, section):
            """section to retun all options on, formatted as an object
            transforms all comma-delimited options to lists
            comma-delimited lists with colons are transformed to dicts
            dicts will have values expressed as lists, no matter the length
            """
            c = ConfigParser.RawConfigParser()
            c.read(os.path.join(os.path.dirname(__file__), 'config.cfg'))
    
            self.section_name = section
    
            self.__dict__.update({k:v for k, v in c.items(section)})
    
            #transform all ',' into lists, all ':' into dicts
            for key, value in self.__dict__.items():
                if value.find(':') > 0:
                    #dict
                    vals = value.split(',')
                    dicts = [{k:v} for k, v in [d.split(':') for d in vals]]
                    merged = {}
                    for d in dicts:
                        for k, v in d.items():
                            merged.setdefault(k, []).append(v)
                    self.__dict__[key] = merged
                elif value.find(',') > 0:
                    #list
                    self.__dict__[key] = value.split(',')
    

    So now my config.cfg file, which could look like this:

    [server]
    credentials=username:admin,password:$3

    Can be parsed into fine-grained-enough objects for my small project.

    >>> import config
    >>> my_server = config.Parser('server')
    >>> my_server.credentials
    {'username': ['admin'], 'password', ['$3>> my_server.loggingdirs:
    ['/tmp/logs', '~/logs', '/var/lib/www/logs']
    >>> my_server.timeoutwait
    '15'
    

    This is for very quick parsing of simple configs, you lose all ability to fetch ints, bools, and other types of output without either transforming the object returned from Parser, or re-doing the parsing job accomplished by the Parser class elsewhere.

提交回复
热议问题