I've never done anything like this before so I'd like someone else to look at this before I get too carried away :)
Am I making this more complicated than it needs to be? I'm trying to make it EASY for other modules/scripts on this system to store and retrieve their settings. Hence why I trap the ConfigParser.NoOptionError
error and return None
and create the section if it doesn't exist in the set()
method.
Suggestions?
import ConfigParser
import os
from ast import literal_eval as Eval
class _ConfParse(ConfigParser.ConfigParser):
def __init__(self, confpath, conffile):
ConfigParser.ConfigParser.__init__(self)
self.conf_file = os.path.join(confpath, conffile)
try: self.readfp(open(self.conf_file), 'r')
except IOError as Err:
if Err.errno == 2: pass
else: raise Err
def set(self, section, option, value):
if self.has_section(section):
ConfigParser.ConfigParser.set(self, section, option, str(value))
else:
self.add_section(section)
ConfigParser.ConfigParser.set(self, section, option, str(value))
def get(self, section, option):
try: return Eval(ConfigParser.ConfigParser.get(self, section, option))
except ConfigParser.NoOptionError: return None
def save(self):
self.write(open(self.conf_file, 'w'))
def __del__(self):
self.save()
class LocalConfig(_ConfParse):
def __init__(self, conffile, confpath = '/etc/local/cnf'):
_ConfParse.__init__(self, confpath, conffile)
class SysConfig(_ConfParse):
def __init__(self, conffile, confpath = '/etc/sys/cnf'):
_ConfParse.__init__(self, confpath, conffile)