• Steam recently changed the default privacy settings for all users. This may impact tracking. Ensure your profile has the correct settings by following the guide on our forums.

Configuration

Nimsical

Hi, I'm Nima
So I started messing around with python about a week and a half ago and I've been using this config class for my apps. Comments and suggestions would be appreciated :)

[highlight=python]
import os.path
import re

class Config:
"""Config Class"""
items = {}
newItems = 0
newKeys = []
def __init__(self, filename):
self['filename'] = filename
if (not os.path.exists(filename)):
print "Config file doesn't not exist!\n";
exit(1);
CONF = open(filename, "r")
while True:
line = CONF.readline()
if (len(line) == 0):
break
line = line.strip()
if (not line or line[:1] == '#'):
continue
srch = re.compile(r'(?P<key>\S+)[ ]*?=[ ]*?(?P<item>.+)', re.IGNORECASE)
self[srch.search(line).group('key').strip()] = srch.search(line).group('item').strip()
CONF.close()
def update(self):
newlines = []
CONF = open(self['filename'], "r")
while True:
line = CONF.readline()
if (len(line) == 0):
break
line = line.strip()
if (not line):
continue
elif (line[:1] == '#'):
newlines.append(line + "\n")
continue
srch = re.compile(r'(?P<key>\S+)[ ]*?=[ ]*?(?P<item>.+)', re.IGNORECASE)
if (srch.search(line) != None):
key = srch.search(line).group('key')
line = "%s = %s\n" % (key, self[key])
newlines.append(line)
CONF.close()
if (self.newItems > 0):
for key in self.newKeys:
line = "%s = %s\n" % (key, self[key])
newlines.append(line)
CONF = open(self['filename'], "w")
CONF.writelines(newlines)
CONF.close()
def newItem(self, key, item):
self.newItems += 1
self.newKeys.append(key)
self[key] = item.strip()
def __setitem__(self, key, item):
self.items[key] = item
def __getitem__(self, key):
try:
ret = self.items[key]
return ret
except:
return None
[/highlight]

The update function updates the configuration in-file (program should call it if values of the items were changed or new items were added). The only thing that might be annoying about it is that it removes all the empty lines in the configuration file.

Sample Config:

Code:
###### User Configuration ######
###### RSS Downloader	  #####
######	v 0.1		  ######
save_dir = /Users/nima/Downloads/Torrents
shows = weeds,greek,house,skins
quality = HDTV
last_update = Wed Aug 26 00:01:27 2009
 
Top