Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically read configuration values in Python

I would like to read a configuration file in Python completely into a data structure without explicitly 'getting' each value. The reason for doing so is that I intend to modify these values programatically (for instance, I'll have a variable that says I want to modify [Foo] Bar = 1 to be [Foo] Bar = 2), with the intention of writing a new configuration file based on my changes.

At present, I'm reading all the values by hand:

parser = SafeConfigParser()
parser.read(cfgFile)
foo_bar1 = int(parser.get('Foo', 'Bar1'))
foo_bar2 = int(parser.get('Foo', 'Bar2'))

What I would love to have (didn't find much Google-wise) is a method to read them into a list, have them be identified easily so that I can pull that value out of the list and change it.

Essentially referencing it as (or similarly to):

config_values = parser.read(cfgFile)
foo_bar1      = config_values('Foo.bar1')
like image 661
the_e Avatar asked Sep 01 '25 16:09

the_e


2 Answers

Sorry if I'm misunderstanding -- This really doesn't seem much different than what you have -- It seems like a very simple subclass would work:

class MyParser(SafeConfigParser):
    def __call__(self,path,type=int):
        return type(self.get(*path.split('.')))

and of course, you wouldn't actually need a subclass either. You could just put the stuff in __call__ into a separate function ...

like image 100
mgilson Avatar answered Sep 04 '25 05:09

mgilson


import sys
from ConfigParser import SafeConfigParser

parser = SafeConfigParser()
parser.readfp(sys.stdin)

config = dict((section, dict((option, parser.get(section, option))
                             for option in parser.options(section)))
              for section in parser.sections())
print config

Input

[a]
b = 1
c = 2
[d]
e = 3

Output

{'a': {'c': '2', 'b': '1'}, 'd': {'e': '3'}}
like image 41
jfs Avatar answered Sep 04 '25 06:09

jfs