author | Radek Brich <radek.brich@devl.cz> |
Tue, 16 Aug 2011 16:03:46 +0200 | |
changeset 9 | 2fcc8ef0b97d |
parent 2 | common/config.py@efee419b7a2d |
child 10 | f3a1b9792cc9 |
permissions | -rw-r--r-- |
2 | 1 |
import logging |
2 |
||
3 |
||
4 |
class ConfigParser: |
|
5 |
def __init__(self): |
|
6 |
self.args = {} # config file arguments |
|
7 |
self.registered_args = {} |
|
8 |
self.log = logging.getLogger('config') |
|
9 |
||
10 |
def add_argument(self, name, type=str, default=None): |
|
11 |
self.registered_args[name] = {'type':type, 'default':default} |
|
12 |
||
13 |
def load(self, fname): |
|
14 |
# parse config file |
|
15 |
with open(fname) as f: |
|
16 |
exec(f.read(), self.args) |
|
17 |
# check contents |
|
18 |
return self.check() |
|
19 |
||
20 |
def check(self): |
|
21 |
ok = True |
|
22 |
for key in self.args.keys(): |
|
23 |
if key == '__builtins__': |
|
24 |
continue |
|
25 |
if key in self.registered_args: |
|
26 |
# arg registered, check type |
|
27 |
type = self.registered_args[key]['type'] |
|
28 |
if not isinstance(self.args[key], type): |
|
29 |
ok = False |
|
30 |
self.log.error("Bad type of config parameter '%s': is %s but should be %s", |
|
31 |
key, type(self.args[key]), type) |
|
32 |
else: |
|
33 |
# arg not registered |
|
34 |
ok = False |
|
35 |
self.log.error("Unknown config parameter '%s'.", key) |
|
36 |
return ok |
|
37 |
||
38 |
def __getattr__(self, name): |
|
39 |
if name in self.args: |
|
40 |
return self.args[name] |
|
9
2fcc8ef0b97d
Reorganize again :-) Add setup.py.
Radek Brich <radek.brich@devl.cz>
parents:
2
diff
changeset
|
41 |
|
2 | 42 |
# raise error if not found |
43 |
raise AttributeError() |
|
44 |