Advertisement
RMDan

Preferences Script

May 12th, 2013
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.39 KB | None | 0 0
  1. import copy
  2. import shutil
  3.  
  4. class Preferences:
  5.     """Simple Class for reading and writing preferences to a file"""
  6.  
  7.     _pref = {}
  8.     _sections = []
  9.    
  10.     def __init__(self, fileName):
  11.         self._file = fileName
  12.         self._loadPreferences_()
  13.  
  14.     def __repr__(self):
  15.         """Defines what happens when the object is printed out"""
  16.         out = ""
  17.  
  18.         for sk,sv in self._pref.items():
  19.             out += "[%s]\n" % (sk)
  20.             for ik,iv in sv.items():
  21.                 out += "%s = %s\n" % (ik,iv)
  22.  
  23.         return out
  24.  
  25.     def _loadPreferences_(self):
  26.         """
  27.        Reads in the preferences's from a file
  28.        Ignores lines that start with # or ; (comments)
  29.        Comments must be on their own line
  30.        """
  31.  
  32.         pref = {}
  33.         pref["Main"] = {}
  34.         sections = ["Main"]
  35.         curSection = "Main"
  36.         fh = open(self._file,"r+")
  37.  
  38.         for line in fh:
  39.             if line[:1] == '#' or line == "\n" or line[:1] == ';':
  40.                 continue
  41.  
  42.             if line[:1] == '[':
  43.                 curSection = line.strip()[1:-1]
  44.                 sections.append(line.strip()[1:-1])
  45.                 pref[curSection] = {}
  46.                 continue
  47.            
  48.             p = line.split('=')
  49.             pref[curSection][p[0].replace('"', '').strip()] = p[1].replace('"', '').strip()
  50.  
  51.         fh.close()
  52.        
  53.         self._pref = pref
  54.         self._sections = sections
  55.  
  56.  
  57.     def getPreferences(self):
  58.         """
  59.        Returns a Deepcopy of a Dictionary
  60.        Contains Dictionaries for each section in preference file
  61.        """
  62.         return copy.deepcopy(self._pref)
  63.    
  64.     def savePreferences(self, pref, backup = False):
  65.         """
  66.        Takes the supplied dictionary and writes it to file
  67.        Curently overrides orginal file
  68.        Optionaly makes backup of original file
  69.        """
  70.         lines = ""
  71.         sections = []
  72.  
  73.         for k in pref.keys():
  74.             sections.append(k)
  75.        
  76.         sections.insert(0, sections.pop(sections.index('Main')))
  77.  
  78.         for section in sections:
  79.             if not section == 'Main':
  80.                 lines += "\n[%s]\n" % (section)
  81.  
  82.             for k,v in pref[section].items():
  83.                 lines += "%s = %s\n" % (k,v)
  84.  
  85.         if backup:
  86.             #Do Backup
  87.             shutil.copy2(self._file,"%s.bak" % (self._file))
  88.  
  89.         fh = open(self._file, "w")
  90.         fh.write(lines)
  91.         fh.close()
  92.  
  93.     def listSections(self):
  94.         """Lists the sections in a preference file"""
  95.         return self._sections
  96.    
  97.     def getDifferences(self, oldPref, newPref):
  98.         """
  99.        Compares two dictionaries and returns a tuple
  100.        The tuple contains 3 dictionaries(changed, inserted, deleted)
  101.        """
  102.         changedPref = {}
  103.         insertPref = {}
  104.         delPref = {}
  105.  
  106.         for k,v in newPref.iteritems():
  107.             if (k not in oldPref):
  108.                 insertPref[k] = v
  109.                 continue
  110.  
  111.             if (not oldPref[k] == v):
  112.                 changedPref[k] = v
  113.  
  114.         for k,v in oldPref.iteritems():
  115.             if (k not in newPref):
  116.                 delPref[k] = v
  117.  
  118.         return updatePref, insertPref, delPref
  119.  
  120.  
  121. if __name__ == "__main__":
  122.     tp = Preferences("test2.ini")
  123.     pref = tp.getPreferences()
  124.     pref["New"] = {}
  125.     pref["New"]["Bad"] = "Good"
  126.     tp.savePreferences(pref)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement