[Tutor] I Give Up.

Python python at venix.com
Sun Jun 18 00:30:16 CEST 2006


On Sat, 2006-06-17 at 16:44 -0400, Brian Gustin wrote:
> Now can someone explan how exactly (preferrably with an actual real 
> world example) that I can read a configuration file in , say 
> /etc/local-config/myconfig.cfg  into my python script running in 
> /usr/bin/localscripts , and able to actually use the names as
> variables 
> (objects) with the configured values assigned to them?

This was done from the Python prompt.  Sorry for the crummy names.  If
you saw all the typos that have been removed, you'd understand why I
kept the names short.


>>> print open('sample.config').read()
[sect_1]
a = 1
b = 2

>>> cfg = cp.SafeConfigParser()
>>> cfg.read('sample.config')
>>> cfg.sections()
['sect_1']
>>> for s in cfg.sections():
...     print cfg.items(s)
...
[('a', '1'), ('b', '2')]
>>> class A:
...     pass
...
>>> a = A()
>>> for s in cfg.sections():
...     setattr(a,s,A())
...     as = getattr(a,s)
...     for k,v in cfg.items(s):
...             setattr(as,k,v)
...
>>> a
<__main__.A instance at 0xb7f0256c>
>>> a.sect_1
<__main__.A instance at 0xb7eda3ac>
>>> a.sect_1.a
'1'
>>> a.sect_1.b
'2'
>>>

Hope this helps.  Note that you can build a section dictionary by:

	sect_dict = dict(cfg.items('section-name'))

You can create a class to turn dict references (d.get('key')) into
object references (o.key) with this trick:

>>> class Better(object):
...     def __init__(self, **kwds):
...             self.__dict__.update(kwds)

sect_obj = Better( **sect_dict)

-- 
Lloyd Kvam
Venix Corp



More information about the Tutor mailing list