Skip to content Skip to sidebar Skip to footer

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 th

Solution 1:

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 ...


Solution 2:

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'}}

Solution 3:

Are you running python 2.7?

There's a nifty way, I discovered a few months back, to parse the config file and setup a dictionary using dictionary comprehension.

config = ConfigParser.ConfigParser()
config.read('config.cfg')
# Create a dictionary of complete config file, {'section':{'option':'values'}, ...}
configDict = {section:{option:config.get(section,option) for option in config.options(section)} for section in config.sections()}

Although this way is harder to read, it take's up less space, and you don't have to explicitly state every variable that you want to get.

  • Note: This won't work on python 2.6 (*that I know of). I've written scripts in the past where I used this, and since I'm running 2.7 on Windows, somebody on a linux machine, running 2.6, will crash on the dictionary comprehension.

--Edit--

You will need to still manually change the data types of the values.


Post a Comment for "Automatically Read Configuration Values In Python"