author | Radek Brich <brich.radek@ifortuna.cz> |
Mon, 14 Apr 2014 22:28:12 +0200 | |
changeset 97 | a4af93e72e2b |
parent 78 | 64c62ac8f65d |
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 = {} |
|
10
f3a1b9792cc9
Added pgconsole. It is my older project, a GUI query console. It uses GTK+ and asynchronous queries.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
8 |
self.log = logging.getLogger('config') |
2 | 9 |
|
10 |
def add_argument(self, name, type=str, default=None): |
|
11 |
self.registered_args[name] = {'type':type, 'default':default} |
|
17
f768a3529ee7
ToolBase - implement 'database' config option.
Radek Brich <radek.brich@devl.cz>
parents:
10
diff
changeset
|
12 |
self.args[name] = default |
2 | 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'] |
|
17
f768a3529ee7
ToolBase - implement 'database' config option.
Radek Brich <radek.brich@devl.cz>
parents:
10
diff
changeset
|
29 |
if not isinstance(self.args[key], type) and not self.args[key] is None: |
2 | 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 |
|
17
f768a3529ee7
ToolBase - implement 'database' config option.
Radek Brich <radek.brich@devl.cz>
parents:
10
diff
changeset
|
35 |
ok = False |
f768a3529ee7
ToolBase - implement 'database' config option.
Radek Brich <radek.brich@devl.cz>
parents:
10
diff
changeset
|
36 |
self.log.error("Unknown config parameter '%s'.", key) |
2 | 37 |
return ok |
38 |
||
39 |
def __getattr__(self, name): |
|
40 |
if name in self.args: |
|
41 |
return self.args[name] |
|
9
2fcc8ef0b97d
Reorganize again :-) Add setup.py.
Radek Brich <radek.brich@devl.cz>
parents:
2
diff
changeset
|
42 |
|
2 | 43 |
# raise error if not found |
44 |
raise AttributeError() |
|
45 |