author | Radek Brich <brich.radek@ifortuna.cz> |
Fri, 16 Aug 2013 13:23:49 +0200 | |
changeset 7 | 776ba4914dfc |
parent 4 | fdaa7dc9035e |
child 12 | d5f749032fa1 |
permissions | -rw-r--r-- |
4 | 1 |
# simple config file parser utilizing Python's exec() builtin |
3 | 2 |
|
3 |
||
4 |
class ConfigParserError(Exception): |
|
5 |
pass |
|
6 |
||
7 |
||
8 |
class ConfigParser: |
|
9 |
def __init__(self): |
|
4 | 10 |
self.options = {} |
11 |
self.values = {} |
|
3 | 12 |
|
7
776ba4914dfc
Update ConfigParser: rename 'type_' back to 'type'. Rename project in setup.py to make RPM package names more standard.
Radek Brich <brich.radek@ifortuna.cz>
parents:
4
diff
changeset
|
13 |
def add_option(self, name, type=str, default=None): |
4 | 14 |
"""Register option name, type and default value.""" |
7
776ba4914dfc
Update ConfigParser: rename 'type_' back to 'type'. Rename project in setup.py to make RPM package names more standard.
Radek Brich <brich.radek@ifortuna.cz>
parents:
4
diff
changeset
|
15 |
self.options[name] = {'type':type, 'default':default} |
4 | 16 |
self.values[name] = default |
3 | 17 |
|
18 |
def load(self, fname): |
|
4 | 19 |
"""Read config file and check loaded values.""" |
20 |
self.read(fname) |
|
3 | 21 |
self.check() |
22 |
||
4 | 23 |
def read(self, fname): |
24 |
"""Read config file. Does not check values.""" |
|
3 | 25 |
with open(fname) as f: |
4 | 26 |
exec(f.read(), self.values) |
3 | 27 |
|
28 |
def check(self): |
|
4 | 29 |
"""Check option values against registered types.""" |
30 |
for key in self.values.keys(): |
|
3 | 31 |
if key == '__builtins__': |
32 |
continue |
|
4 | 33 |
if key in self.options: |
34 |
type_ = self.options[key]['type'] |
|
35 |
if not isinstance(self.values[key], type_) and not self.values[key] is None: |
|
3 | 36 |
raise ConfigParserError("Bad value of config parameter '%s': type is %s but should be %s" |
4 | 37 |
% (key, type(self.values[key]), type_)) |
3 | 38 |
else: |
39 |
raise ConfigParserError("Unknown config parameter '%s'." % key) |
|
40 |
||
41 |
def __getattr__(self, name): |
|
42 |
"""Attribute access for config parameters. |
|
43 |
||
4 | 44 |
cfg.my_param <===> cfg.values['myparam'] |
3 | 45 |
|
46 |
""" |
|
4 | 47 |
if name in self.values: |
48 |
return self.values[name] |
|
3 | 49 |
else: |
50 |
raise AttributeError() |
|
51 |