|
From: Michael F. <mi...@pc...> - 2005-11-03 16:36:30
|
m.g...@gm... wrote:
> Michael Foord schrieb:
>
>> Ok - I'll try and add an example. It is slightly weird. (Which for
>> reference allows you to change the name and values of a ConfigObj by
>> passing in a single function).
>
>
>
> to generate configfiles from a template
> simple e.g.
> [XXXXX_section]
> key1 = blalba\XXXXX\value1.txt
>
> [CLIENT1_section]
> key1 = blalba\CLIENT1\value1.txt
>
> [CLIENT2_section]
> key1 = blalba\CLIENT2\value1.txt
> Marc
> ps. ok, i can replace XXXXX with CLIENT1 or CLIENT2, because your
> module is more elegant ;-).
>
>
You can use the ``encode`` and ``decode`` section methods as examples of
using the walk method. You use the ``rename`` method to change the name
of a key.
Suppose you want to change 'XXXX' in values *and* names into 'CLIENT1',
you define a function to do the transformation.
A function passed to the walk method needs the argument signature :
(section, key)
Values can be lists or strings, or if the value is a section it will be
a dictionary. Suppose we ignore lists and only do the replace on strings.
So we define our function :
def transform(section, key):
val = section[key]
if isinstance(val, (list, tuple, dict)):
newval = val
else:
newval = val.replace('XXXX', 'CLIENT1')
newkey = key.replace('XXXX', 'CLIENT1')
section.rename(key, newkey)
section[newkey] = newval
So you can then call :
config = ConfigObj(filename)
config.walk(transform, call_on_sections=True)
Does that help ?
All the best,
Fuzzyman
http://www.voidspace.org.uk/python
|