Inifile: an ini-style configuration template
IniFile is a ini-style configuration module that uses a template to define the configuration file structure. The code below includes some samples. Feel free to use as-is.
"""
inifile.py
Library for reading and writing ini-style config files. The ini file
structure is provided as a class, with nested classes acting as the
sections.
Usage:
# declare the ini file structure using a class statement
class MyIni(IniFile):
one = TypedAttribute(1)
two = TypedAttribute(2)
three = TypedAttribute(3, name='triple')
class NestedSection(IniSection):
str1 = TypedAttribute('one', name='str_one')
str2 = TypedAttribute('two', name='str_two')
# create a configuration instance
config = MyIni()
# read the config file
inifile.load()
or
inifile.read()
# write it back
inifile.save()
or
inifile.write()
-- sample ini file --
[server]
socketPort = 8080
threadPool = 10
[staticContent]
bitmaps = /var/local/bitmaps
[session]
storageType=ram
"""
from metatemplate import GenericTemplate, GenericAttribute, TypedAttribute, next_attribute_id
from types import StringType
from inspect import isclass
import re
debug_inifile = 0
class IniSection(GenericTemplate):
re_section = re.compile(r'^\[(.*)\]')
re_unquote = re.compile(r'^(?P[\"\']?)(?P .*)(?P=openquote)$')
def log(self, line):
"""simple auxiliary log functions"""
if debug_inifile:
# should use the logger interface!
print line
def unquote(self, value):
"""unquotes strings reads from the config file"""
return self.re_unquote.match(value).groupdict()['content']
def read(self, fileobj):
"""reads the config file info from a file-like object"""
for line in fileobj:
#attr_name_list = [f[0] for f in self.__fields__]
attr_name_list = self.__attr__.keys()
line = line.strip()
if not line: continue
matchresult = self.re_section.match(line)
if matchresult:
sectionname = matchresult.group(1)
self.log('Found section: %s' % sectionname)
while sectionname in attr_name_list:
# found a known section
section = getattr(self, sectionname, None)
if isinstance(section, IniSection):
self.log('Section: %s' % sectionname)
sectionname = section.read(fileobj)
self.log('Section finished: %s' % sectionname)
else:
# section name does refer to a section object
# ?should it raise a fatal exception/warning?
self.log('Section error: %s' % sectionname)
sectionname = None
else:
# section is not a child of this node, it's a
# sibling; returns the section name
self.log('Unknown section: %s' % sectionname)
return sectionname
else:
# found an attribute
name, value = line.split('=',1)
name = name.strip()
value = value.strip()
self.log('Normal attribute: %s = %s' % (name, value))
# retrieves the attribute using the alternative name
cls_attr_tuple = self.__class__.__attr__.get(name, None)
if not cls_attr_tuple:
# invalid attribute found in the config file!
# ? should it cause a exception or warning ?
print '1:', self.__class__.__fields__
print '2:', self.__class__.__attr__
print '3:', self.__class__.__attr__[name]
print '4:', cls_attr_tuple
print 'Error - Attribute not found: %s' % (name,)
raise KeyError
# retrieves the name used for binding
cls_attr_name, cls_attr = cls_attr_tuple
# sets the instance value
if isinstance(cls_attr, GenericAttribute):
setattr(self, cls_attr_name, self.unquote(value))
else:
# invalid attribute found in the config file!
# ? should it cause a exception or warning ?
raise KeyError
def write(self, fileobj, _initialpos = None):
"""writes the config file info to a file-like object"""
if not _initialpos:
_initialpos = fileobj.tell()
for fname, fobj in self.__fields__:
# looks at the class to retrieve the attribute definition
cls_attr = getattr(self.__class__, fname, None)
# gets the attribute value stored in the instance
ins_attr = getattr(self, fname, None)
# is a subsection?
if isclass(cls_attr) and issubclass(cls_attr, IniSection):
# writes an empty line before the section (if needed)
currentpos = fileobj.tell()
if currentpos > _initialpos:
fileobj.write('\n')
# writes section name & section contents
fileobj.write('[%s]\n' % fname)
ins_attr.write(fileobj, _initialpos = currentpos)
# is an attribute?
elif isinstance(cls_attr, GenericAttribute):
fileobj.write('%s=%s\n' % (cls_attr.name, str(ins_attr)))
class IniFile(IniSection):
def load(self, fname=None):
if not fname:
fname = self.name + '.ini'
inifile = open(fname, 'r')
self.read(inifile)
inifile.close()
def save(self, fname=None):
if not fname:
fname = self.name + '.ini'
inifile = open(fname, 'w')
self.write(inifile)
inifile.close()
15 Comments:
At November 19, 2005 at 4:30 PM, Anonymous said…
Well done on a nice blog Carlos Ribeiro. I was looking for information on work from home data entry and came across your post Inifile: an ini-style configuration template - not precisely what I was looking for related to work from home data entry but an interesting read all the same!
At December 12, 2005 at 10:49 AM, Anonymous said…
Hi Carlos Ribeiro,
great info on your blog Inifile: an ini-style configuration template I was really looking for information in more detail on data entry however I still found your read to be quite informative and interesting. Thanks for the useful info
At January 14, 2006 at 6:21 PM, Anonymous said…
Hi there Carlos Ribeiro, I was just browsing, looking for Work at Home blogs and found yours. Very Nice! If you're a stay-at-home mom, student, home maker or just someone in need of some extra cash, here's an Ideal Opportunity! You can get paid submitting and entering data online and make an extra $300-$1000+ per day with only 30 mins daily. Go to work at home jobs for more info and to join! It's RISK FREE with a 60-day
money back guarantee. :)
At February 13, 2007 at 8:08 AM, Anonymous said…
Great blog very informative re direct line underwriter. In a simliar vain to direct line underwriter would definitely recommend http://www.bargainplace.co.uk for **cheap car insurance** or **cheap home insurance**, even **cheap pet insurance**
At August 18, 2007 at 6:05 PM, Anonymous said…
Great article! Thanks.
At August 18, 2007 at 11:24 PM, Anonymous said…
Thanks for interesting article.
At September 10, 2007 at 4:07 PM, Anonymous said…
Excellent website. Good work. Very useful. I will bookmark!
At March 4, 2013 at 5:07 PM, Anonymous said…
the specific model of your device and then muggy just raise up your legs to raise the [url=http://www.baseeur.com/]louboutin outlet[/url]are a necessary ingredient to ensuring the at the Frade Field and return to operations [url=http://www.baseeur.com/]louboutin outlet uk[/url]on I in no way had night sweats over again Not so many years ago I was diagnosed with [url=http://www.baseeur.com/]louboutin shoes[/url]Deadly Shot Delivers heavy destroy to a creatures Foxes default Various others http://www.baseeur.com[/url] be straight to the point and step by step will provide guests that book their
At March 8, 2013 at 11:05 AM, Anonymous said…
What computer software were computers using before Microsoft
was invented?
Here is my website: transvaginal mesh lawsuit
At March 27, 2013 at 3:31 PM, Anonymous said…
You've made some good points there. I looked on the internet for more info about the issue and found most individuals will go along with your views on this website.
Feel free to surf to my web site; root canal treatment
At April 17, 2013 at 9:58 AM, Anonymous said…
I enjoy reading a post that can make people think.
Also, thank you for allowing me to comment!
Also visit my website - Cost of dental implant
At May 9, 2013 at 1:34 PM, Anonymous said…
I blog frequеntly anԁ I really appгесiate your contеnt.
Thіs articlе haѕ really peaκed my inteгest.
I'm going to book mark your website and keep checking for new information about once a week. I subscribed to your Feed too.
Also visit my web page: Mid Stakes Offer
At June 9, 2013 at 5:35 PM, Anonymous said…
Hi theгe would you mіnd letting me κnoω ωhich
webhost you're utilizing? I've loadeԁ уоuг blog in 3 different іnteгnet browѕers аnԁ Ӏ must ѕаy this blоg loads a
lot fastеr thеn most. Ϲan you suggeѕt a good hosting proviԁeг at a faіг price?
Mаnу thanks, I appreсiate it!
Review my ѕitе; AmericasCardRoom Promotions
At March 4, 2016 at 8:33 PM, Anonymous said…
ninest123 16.03
prada outlet, nike outlet, longchamp outlet, burberry outlet, gucci handbags, ralph lauren polo, cheap jordans, louis vuitton outlet, louis vuitton outlet online, oakley sunglasses, uggs on sale, louis vuitton outlet, tiffany jewelry, replica watches, ralph lauren outlet, michael kors outlet, longchamp outlet, cheap oakley sunglasses, ray ban sunglasses, michael kors handbags, replica watches, michael kors outlet online, oakley sunglasses, uggs on sale, louboutin shoes, christian louboutin, ray ban sunglasses, uggs outlet, nike free, christian louboutin, uggs outlet, tiffany jewelry, nike air max, oakley sunglasses, longchamp bags, uggs on sale, michael kors outlet online, michael kors outlet online, nike air max, louis vuitton handbags, oakley sunglasses, louis vuitton, ray ban sunglasses, louboutin uk, michael kors, tory burch outlet, burberry factory outlet, prada handbags
At March 4, 2016 at 8:33 PM, Anonymous said…
lunette oakley pas cher, nike roshe run pas cher, lululemon outlet, hollister uk, jordan pas cher, coach purses, lunette ray ban pas cher, nike tn pas cher, hogan sito ufficiale, abercrombie and fitch, new balance, longchamp soldes, nike blazer pas cher, true religion outlet, true religion outlet, michael kors, replica handbags, michael kors, sac guess pas cher, ray ban uk, nike air max, mulberry uk, vans pas cher, abercrombie and fitch UK, louboutin pas cher, nike air max pas cher, coach outlet store online, nike free pas cher, true religion jeans, polo lacoste pas cher, true religion outlet, nike air max uk, ralph lauren pas cher, kate spade outlet, longchamp pas cher, nike air force, polo ralph lauren uk, hermes pas cher, michael kors uk, north face uk, timberland pas cher, vanessa bruno pas cher, nike free, michael kors outlet online, coach outlet, nike air max uk, burberry pas cher, north face pas cher, converse
Post a Comment
<< Home