-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathread_config.py
67 lines (53 loc) · 1.81 KB
/
read_config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 13 21:27:44 2017
@author: wroscoe
"""
import os
import types
class Config:
def from_pyfile(self, filename, silent=False):
#filename = os.path.join(self.root_path, filename)
d = types.ModuleType('config')
d.__file__ = filename
try:
with open(filename, mode='rb') as config_file:
exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
except IOError as e:
e.strerror = 'Unable to load configuration file (%s)' % e.strerror
raise
self.from_object(d)
return True
def from_object(self, obj):
for key in dir(obj):
if key.isupper():
#self[key] = getattr(obj, key)
setattr(self, key, getattr(obj, key))
def __str__(self):
result = []
for key in dir(self):
if key.isupper():
result.append((key, getattr(self,key)))
return str(result)
def show(self):
for attr in dir(self):
if attr.isupper():
print(attr, ":", getattr(self, attr))
def load_config(config_path=None):
if config_path is None:
import __main__ as main
main_path = os.path.dirname(os.path.realpath(main.__file__))
config_path = os.path.join(main_path, 'config.py')
if not os.path.exists(config_path):
local_config = os.path.join(os.path.curdir, 'config.py')
if os.path.exists(local_config):
config_path = local_config
print('loading config file: {}'.format(config_path))
cfg = Config()
cfg.from_pyfile(config_path)
print("final settings:")
#cfg.show()
print()
print('config loaded')
return cfg