Parsing a conf file
Gerhard Häring
gh at ghaering.de
Wed Mar 5 16:10:45 EST 2003
John Hunter wrote:
>>>>>> "Simon" == Simon Faulkner <news at titanic.co.uk> writes:
>
> Simon> Hello All, Is there a simple / recommended way of parsing a
> Simon> setting from a conf file?
>
>
> Simon> server = Stafford
>
> It depends somewhat on the format of the whole file, but for a first
> pass
>
> conf = {}
> for line in file('test.conf'):
> vals = line.split('=')
> if len(vals)!=2: continue
> key, val = vals
> conf[key.strip()] = val.strip()
Instead of the check wether only one equal sign is found in the line,
I'd rather do:
vals = line.split('=', 1)
This second "maxsplit" argument to split is often quite useful :-)
Of course if the file really has Python syntax, you could just use
execfile as a quick hack:
---------8<-----------------------
# This is the config file
smtp_server = "mail.my.domain.test"
--------->8-----------------------
---------8<-----------------------
def get_config(filename):
my_globals, my_locals = {}, {}
execfile(filename, my_globals, my_locals)
return my_locals
--------->8-----------------------
-- Gerhard
More information about the Python-list
mailing list