ems/Config/config.py
2014-01-30 18:42:36 +01:00

119 lines
3.6 KiB
Python

'''
Created on 21.11.2013
@author: Philipp Rauch
'''
from sys import stderr, exit
config = "config\ems.conf"
class Config():
_instance = None
_confDic = {
'mySQL_server': '',
'mySQL_port': '3306',
'mySQL_user': '',
'mySQL_pass': '',
'mySQL_database': '',
'mySQL_speed' : '0.02',
'flask_server': '0.0.0.0',
'flask_port': '5000',
'config_debug' : False,
'config_read' : False,
'config_dictionary' : 'config',
'can_baudrate' : '500k',
'can_symfile' : ''
}
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 }\n' % 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
_linenumber = 0
for line in confFile:
_linenumber += 1
line = line.strip()
if len(line) == 0 or line[0] == "#": #remove empty lines and comments
continue
if line.find("=") == -1:
exit('config_error: an error has occurred in line %s\r' % _linenumber)
key, arg = self.getElement(line)
if key == None:
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
for key in self._confDic:
if self._confDic[key] == '':
exit('please select a value for {0}'.format(key))
if self._confDic['config_debug']:
self.printConf()
return self._confDic
c = Config()
conf = c.readConf()