''' Created on 21.11.2013 @author: Philipp Rauch ''' from sys import stderr, exit _config_dir = 'config' _config_file = 'ems.conf' _config_path = _config_dir + '/' + _config_file 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_dir, '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_path, "r") except IOError: self._confDic.update({'error' : '%s not found' % _config_path}) stderr.write('config_error %s not found\r' % _config_path) 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()