Welcome, guest | Sign In | My Account | Store | Cart

Python includes the ConfigParser module in its library, which is able to read .ini files. To make the configuration code more readable, I wrote this Configuration class, which parses an .ini file and lets you access the configuration info through its members. Please see the test code (after the #Test comment) for an example of use!

Python, 58 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from ConfigParser import SafeConfigParser

class Configuration:
    def __init__ (self, fileName):
        cp = SafeConfigParser()
        cp.read(fileName)
        self.__parser = cp
        self.fileName = fileName
        
    def __getattr__ (self, name):
        if name in self.__parser.sections():
            return Section(name, self.__parser)
        else:
            return None
            
    def __str__ (self):
        p = self.__parser
        result = []
        result.append('<Configuration from %s>' % self.fileName)
        for s in p.sections():
            result.append('[%s]' % s)
            for o in p.options(s):
                result.append('%s=%s' % (o, p.get(s, o)))
        return '\n'.join(result)

class Section:
    def __init__ (self, name, parser):
        self.name = name
        self.__parser = parser
    def __getattr__ (self, name):
        return self.__parser.get(self.name, name)

# Test
if __name__ == '__main__':
    ''' To run this test, create a file named Importador.ini with this content:
    [Origem]
    host=pcmartin
    port=1521
    sid=dbglobal
    user=portaled1
    password=portaled1
    
    [Destino]
    host=server2
    port=1522
    sid=dbglobal
    user=portaled2
    password=portaled2    
    '''
    # The classic way:
    cp = SafeConfigParser()
    cp.read('Importador.ini')
    print cp.get('Origem', 'host'), cp.get('Origem', 'port')
    # The sexy way ;-)
    c = Configuration('Importador.ini')
    print c.Origem.host, c.Origem.port
    # An extra: print the configuration object itself
    print c

It doesn’t write configurations, it’s only able to read. If somebody wants to create the write functionality, be welcome!

2 comments

Michael Foord 16 years, 4 months ago  # | flag

ConfigObj. Sorry - can't resist it. An easier way to read and write config files is using ConfigObj - http://www.voidspace.org.uk/python/configobj.html

It presents a dictionary interface (members rather than attributes) - which IMHO is more Pythonic (a config file is well represented by a mapping object) and less limited (you can't use some values as attributes (e.g. print) - so you have to provide another way of accessing members, which violates - 'there should be only one obvious way to do it').

config = ConfigObj(filename)
value1 = config['member1']
value2 = config['member2']

or

config = ConfigObj()
config.filename = filename
config['member1'] = value1
config['member2'] = value2
config.write()

Not only this - but ConfigObj 4 is nearly ready. It's all implemented except for preserving comments and the writein method. It has a powerful interface to a validation schema, but the main change is that it will read sections nested to any arbitrary depth using indentation. (But will still read and write simple INI files). This version has no external dependencies.

Fetch it from :

https://svn.rest2web.python-hosting.com/branches/configobj4/

alexandre.rouillac 13 years, 2 months ago  # | flag

how to get the name of sections if unknown ?

Created by Martin Elsner on Wed, 22 Jun 2005 (PSF)
Python recipes (4591)
Martin Elsner's recipes (1)

Required Modules

Other Information and Tasks