File: iniparser.py

package info (click to toggle)
atheist 0.20110402-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 1,348 kB
  • sloc: python: 4,764; xml: 626; makefile: 113; cpp: 54; ansic: 5; sh: 5
file content (67 lines) | stat: -rwxr-xr-x 1,730 bytes parent folder | download | duplicates (3)
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
59
60
61
62
63
64
65
66
67
#!/usr/bin/python
# -*- coding:utf-8; tab-width:4; mode:python -*-

import ConfigParser

class IniParser(ConfigParser.SafeConfigParser):

    default_section = 'DEFAULT'

    class Section:
        def __init__(self, parser, section_name):
            self.parser = parser
            self.section_name = section_name

        def keys(self):
            return [k for k,v in self.items()]

        def items(self):
            return self.parser.items(self.section_name)

        def __getattr__(self, key):
            try:
                return self.parser.get(self.section_name, key)
            except ConfigParser.NoOptionError:
                raise AttributeError(key)

        def __str__(self):
            return "<Section '%s:%s'>" % (self.parser.fname, self.section_name)



    def __init__(self, fname=None):
        self.fname = fname
        ConfigParser.SafeConfigParser.__init__(self)
        if fname:
            self.read(fname)

    def keys(self):
        return self.Section(self, self.default_section).keys()


    def __getitem__(self, path):
        if '.' in path:
            section, key = path.split('.')
        else:
            section, key = self.default_section, path

        return getattr(self.Section(self, section), key)


    def __getattr__(self, section):
        if section.startswith('__'):
            raise AttributeError(section)

        if not self.has_section(section):
            raise ConfigParser.NoSectionError(section)

        return self.Section(self, section)


    def safe_get(self, path, default=None):
        try:
            return self[path]
        except AttributeError,e:
            if default is not None:
                return default
            raise