ems/src/config.py

129 lines
4 KiB
Python
Raw Normal View History

'''
Created on 21.11.2013
@author: Philipp Rauch
'''
2013-11-29 15:04:02 +01:00
from sys import stderr
2013-12-13 12:34:24 +01:00
2013-11-29 15:04:02 +01:00
config = "config\ems.conf"
class Config():
_instance = None
_confDic = {
'mySQL_server': 'localhost',
'mySQL_port': '3306',
'mySQL_user': 'smoke',
'mySQL_pass': 'KiWujcafAlor',
'mySQL_database': 'smoke_test',
#'mySQL_table': 'battery',
'mySQL_speed' : '0.1',
'flask_server': '0.0.0.0',
'flask_port': '5000',
'flask_debug': False,
'config_debug' : False,
'config_read' : False
}
def __new__(cls, *args, **kwargs):
# http://stackoverflow.com/questions/42558/python-and-the-singleton-pattern
if not cls._instance:
cls._instance = super(Config, cls).__new__(
cls, *args, **kwargs)
return cls._instance
def printConf(self):
'''
Print the config only if debug is enable.
'''
if self._confDic['config_debug']:
mes = 'config:\t{'
for x in self._confDic:
mes = '%s\r %s \t: %s' % (mes, x, self._confDic[x])
mes = '%s\r }' % mes
print mes
def makeList(self, arg):
for a in range(len(arg)):
arg[a] = arg[a].strip()
arg[a] = True if arg[a] == 'True' else arg[a]
arg[a] = False if arg[a] == 'False' else arg[a]
return arg
def getElement(self, line):
tmp = line.split("=")
key = tmp[0].strip()
val = tmp[1].split("#") #cut off comments, comment is on val[1]
val = str(val[0].strip()) #overwrite val with string
if key == '':
stderr.write('config_error there is an empty key\r')
return None, None
if val == '':
stderr.write('config_error %s has no value\r' % key)
return None, None
arg = val.split(',')
while arg.count('') > 0:
arg.remove('')
if len(arg) == 0:
stderr.write('config_error %s has an empty argument\r' % key)
return None, None
return key, arg
def readConf(self):
if self._confDic['config_read']: #prevent re-read
return self._confDic
try:
confFile = open(config, "r")
except IOError:
self._confDic.update({'error' : '%s not found' % config})
stderr.write('config_error %s not found\r' % config)
return self._confDic
# master = None
for line in confFile:
line = line.strip()
if len(line) == 0 or line[0] == "#": #remove empty lines and comments
# master = None
continue
if line[0] == '\'':
line = line.lstrip('\'')
# if master is not None:
key, arg = self.getElement(line)
2013-12-13 12:34:24 +01:00
if key == None:
continue #skip errors
res = []
for a in arg:
tmp = a.split(':')
for t in tmp:
res.append(t.strip())
arg = dict(res[i:i+2] for i in range(0, len(res), 2))
### prepared for more dimensional dictionaries ###
# elif line.find(':') != -1:
# master = line.split(':')[0]
# key = master
# arg = None
# pass
elif line.find("=") != -1:
key, arg = self.getElement(line)
if key == None:
2013-12-13 12:34:24 +01:00
continue #skip errors
self.makeList(arg)
arg = arg if len(arg) > 1 else arg[0]
self._confDic[key] = arg
confFile.close()
self._confDic['config_read'] = True
self.printConf()
return self._confDic
c = Config()
conf = c.readConf()