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 self.args[name] = default |
|
13 |
|
14 def load(self, fname): |
|
15 # parse config file |
|
16 with open(fname) as f: |
|
17 exec(f.read(), self.args) |
|
18 # check contents |
|
19 return self.check() |
|
20 |
|
21 def check(self): |
|
22 ok = True |
|
23 for key in self.args.keys(): |
|
24 if key == '__builtins__': |
|
25 continue |
|
26 if key in self.registered_args: |
|
27 # arg registered, check type |
|
28 type = self.registered_args[key]['type'] |
|
29 if not isinstance(self.args[key], type) and not self.args[key] is None: |
|
30 ok = False |
|
31 self.log.error("Bad type of config parameter '%s': is %s but should be %s", |
|
32 key, type(self.args[key]), type) |
|
33 else: |
|
34 # arg not registered |
|
35 ok = False |
|
36 self.log.error("Unknown config parameter '%s'.", key) |
|
37 return ok |
|
38 |
|
39 def __getattr__(self, name): |
|
40 if name in self.args: |
|
41 return self.args[name] |
|
42 |
|
43 # raise error if not found |
|
44 raise AttributeError() |
|
45 |
|