I l@ve RuBoard Previous Section Next Section

4.12 Reading INI Configuration Files

Credit: Dirk Holtwick

4.12.1 Problem

You want to load a configuration file for your program, but you don't want to use a Python module for this purpose, as that might expose you to security risks or troublesome syntax and other errors in the module.

4.12.2 Solution

The standard ConfigParser library module gives us almost all we need to use INI files for configuration:

import ConfigParser
import string

_ConfigDefault = {
    "database.dbms":            "mysql",
    "database.name":            "",
    "database.user":            "root",
    "database.password":        "",
    "database.host":            ""

def LoadConfig(file, config={}):
    returns a dictionary with keys of the form
    <section>.<option> and the corresponding values
    config = config.copy(  )
    cp = ConfigParser.ConfigParser(  )
    for sec in cp.sections(  ):
        name = string.lower(sec)
        for opt in cp.options(sec):
            config[name + "." + string.lower(opt)] = string.strip(
                cp.get(sec, opt))
    return config

if _ _name_ _=="_ _main_ _":
    print LoadConfig("some.ini", _ConfigDefault)

4.12.3 Discussion

Many people use Python modules as configuration files, but this may allow your program to be manipulated or let a syntax error come into that file. To use INI-style configuration files, which are known from Windows (but can also be used under Unix-like systems, since they're just text files with some structure), try the small script here.

The code in the recipe is just for reading configuration files, but writing them is also easy to implement. An INI file looks like this:

user = dummy
password = tosca123

You can set the defaults in advance. Note that the keys of the dictionary are always lowercase.

4.12.4 See Also

Documentation for the ConfigParser module in the Library Reference.

    I l@ve RuBoard Previous Section Next Section