2 Global configuration objects.
4 Joe Presbrey <presbrey@mit.edu>
7 from ConfigParser import ConfigParser, NoSectionError, NoOptionError
10 _ENV_BASE='_SQL_MIT_EDU'
12 class Section(object):
13 """Configuration section namespace."""
14 def __init__(self, d):
17 def __getattr__(self, k):
18 v = self.items.get(k, None)
20 if str(int(v)) == str(v): v = int(v)
21 except TypeError: pass
22 except ValueError: pass
24 if str(v).lower() == 'true': v = True
25 if str(v).lower() == 'false': v = False
26 except TypeError: pass
27 except ValueError: pass
31 return iter(self.items)
34 return str(self.items)
37 """Base configuration namespace."""
38 def __init__(self, filename, *args, **kwargs):
39 self._cp = ConfigParser(*args, **kwargs)
41 self._none = Section({})
43 def _samefile(self, f1, f2):
45 return os.path.samefile(f1, f2)
49 def read(self, filename):
50 config_path = [os.path.join(x, filename) for x in [
51 os.path.dirname(__file__),
53 if _ENV_BASE in os.environ:
54 config_path.insert(1, os.path.join(os.environ[_ENV_BASE], 'etc', filename))
56 r = os.path.join(path, filename)
57 if not r in config_path:
59 if 'HOME' in os.environ:
60 append(os.environ['HOME'])
61 if 'PWD' in os.environ:
62 append(os.environ['PWD'])
63 self._cp.read(config_path)
64 self._sections = dict(map(lambda x: (x, Section(dict(self._cp.items(x)))),
67 def get(self, *av, **kw):
68 try: return self._cp.get(*av, **kw)
69 except NoSectionError: return None
70 except NoOptionError: return None
72 def __getattr__(self, k):
73 return self._sections.get(k, self._none)
77 for x in self._cp.sections():
78 d[x] = dict(self._cp.items(x))
81 if __name__ == '__main__':