#!/usr/bin/env python ''' read and write configuration This Class is derived mainly from 'gimini' project. Thanx to Dutoit! ''' from ConfigParser import * import sys, os ### Set the Preferences filename class Preferences: """ This class handles preferences and stores them into given configfile To use it : - instanciate a Preferences object : myPP=Preferences() - to get a preference : mypref=myPP["ma_preference"] - to set a preference : myPP["ma_preference"]=xxx The preferences are automatically loaded on the first instanciation of this class and are saved when a value is added or changed automatically, too. """ def __init__(self, filename): """ Constructor @author C.Dutoit """ self.prefsfilename = filename self._config = None self.__loadConfig() #>-------------------------------------------------------------------------- def __getitem__(self, name): """ Return the preferences for the given item @param String name : Name of the item for which we return a value @return String : value of the pref, or None if inexistant @since 1.1.2.7 @author C.Dutoit """ if not self._config.has_section("Main"): print "No section: \"[Main]\"" return None try: return self._config.get("Main", name) except NoOptionError: print "No such option: \"" + name +"\"" return None #>-------------------------------------------------------------------------- def __setitem__(self, name, value): """ Return the preferences for the given item @param String name : Name of the item WITHOUT SPACES @param String Value : Value for the given name @raises TypeError : if the name contains spaces @since 1.1.2.7 @author C.Dutoit """ # Add 'Main' section ? if not self._config.has_section("Main"): self._config.add_section("Main") if " " in list(name): raise TypeError, "Name cannot contain a space" # Save self._config.set("Main", name, str(value)) self.__saveConfig() #>-------------------------------------------------------------------------- def __saveConfig(self): """ Save datas to config file @since 1.1.2.5 @author C.Dutoit """ f=open(self.prefsfilename, "w") self._config.write(f) f.close() #>-------------------------------------------------------------------------- def __loadConfig(self): """ Load datas from config file @since 1.1.2.5 @author C.Dutoit """ # Make sure that the configuration file exist try: f = open(self.prefsfilename, "r") f.close() except: try: f = open(self.prefsfilename, "w") f.write("") f.close() except: print "Can't make %s for saving preferences !" % self.prefsfilename return # Read datas self._config=ConfigParser() self._config.read(self.prefsfilename) #>-------------------------------------------------------------------------- if __name__ == "__main__": myPP=Preferences() mypref=myPP["ma_preference"] myPP["ma_preference"]="xxx"