lightweight human-readable config?
Corey Coughlin
corey.coughlin at attbi.com
Fri Oct 31 13:32:07 EST 2003
I actually have a whole set of programs that use a format like this,
it's actually parsed on spaces and keywords, so you just say:
keyword1 value1 value2 value3
keyword2 value1
keyword3
value1
value2
and so on. It's pretty free format, and relatively easy to parse, all
you need to set up is a list of keywords, and in return from these
functions you get a dictionary with the value lists for each keyword.
You can also add comments by adding '#' signs, and the rest of the
line is a comment. Here are the functions:
def ParseCommandFile(commfn, commkeys):
commwords = ReadCommandFile(commfn)
return ParseList(commwords, commkeys)
def ReadCommandFile(commfn):
if not (commfn and os.path.exists(commfn):
raise OSError, "Can't find this path: %s" % fname
commf = open(commfn,'r')
commtext = ''
for line in commf:
if '#' in line:
line = line[:string.find(line,'#')]
commtext = commtext + ' ' + line
commf.close()
commwords = string.split(commtext)
return commwords
def ParseList(commlist, commkeys):
commvals = {}
for ck in commkeys:
commvals[ck] = []
currkey = ''
currval = []
foundkeys = commkeys[:]
for cword in commlist:
if currkey:
if cword in foundkeys:
commvals[currkey] = currval
currkey = cword
foundkeys.remove(currkey)
currval = []
else:
currval.append(cword)
else:
if cword in foundkeys:
currkey = cword
foundkeys.remove(currkey)
if currkey:
commvals[currkey] = currval
return commvals
There it is, maybe not the most efficient code, but it lets you write
a command file parsed on spaces, so there's no need to worry about
extra syntax characters, which keeps it nice and clean.
Maxim Khesin <max at cNvOiSsiPoAnMtech.com> wrote in message news:<p4Xnb.17367$Gq.5475490 at twister.nyc.rr.com>...
> I want to have a config file with my python proggie, satisfying the
> following requirements:
> 1) support key->(value, default)
> 2) simple and intuitive to read and edit
> 3) easyly readable into a python datastructure (a dictionary?)
> 4) not requiring any heavy libraries needed (I am distributing my
> proggie as a py2exe executable and do not want to bloat the size)
>
> can you guys suggest some format for this? thanks,
> max
More information about the Python-list
mailing list