[Tutor] reading configuration file

Gonçalo Rodrigues op73418 at mail.telepac.pt
Tue Nov 11 06:43:36 EST 2003

On Tue, 11 Nov 2003 11:07:45 +0100, you wrote:

>Hi all
>I've made a prog that reads a configuration file. While it works, I think it is
>butt-ugly and defintely not the way it should be done in Python.
>I tried to understand dictionaries and I tried to make eval() work. I failed. 
>What is the good Python way to do what I do below?
>config file:
># parameter settings for pump board and fan boards
># from six fans and pump controller
># pump controller settings
>CO2_soll		 80
>pump_1_manual_override    0  
>pump_1_manual_speed     120
>pump_2_manual_override    0  
>pump_2_manual_speed     130 
># Fan board settings:
>fan_manual_override    0  
>fan_manual_speed     140 

As you mention the best way to do this is to fill a dictionary where
the keys are the "titles" and the values the numbers.

Let me first fire up the interpreter and show you a typical use of a

>>> #Create an empty dictionary.
>>> dct = {}
>>> print dct
>>> #Add a key, value pair.
>>> dct["my key"] = "my value"
>>> print dct
{'my key': 'my value'}
>>> #Rebind the associated value of the key.
>>> dct["my key"] = 0
>>> print dct
{'my key': 0}

This is enough for what we want to do. The idea is

- read file
- parse the contents into a dictionary

From what I gleaned from your code there are also default values,
filled up at initialization time. We can start there and instead of
having a bunch of global variables we just stuff everything in a
(global) dictionary. As in:

DEFAULTDICT = {"CO2_soll": 81,
               "pump_1_manual_override": 1,
               "pump_1_manual_speed": 121,
               "pump_2_manual_override": 1,
               "pump_2_manual_speed": 131,
               "fan_manual_override": 1,
               "fan_manual_speed": 141}

We use capital letters to signal that this is a constant and the user
should not modify this dictionary in any way.

Now we want to code a function, call it parse, that receives the
*contents* of a file, a string, and parses it. A rule of thumb is that
each function does only one thing. As such we *do not* put things like
opening files and handling IO error conditions inside it.

The usage of the function we envision is as in

#Open file: filename is... the filename.
f = file(filename)
    #Read whole file as one string.
    data = f.read()
    #Close file
#Parse data string.
config = parse(data)

Now we can go on with the function. Since we receive data as a string
we must first split it in lines and then we go through each line
reading it, putting the values inside the dictionary.

def parse(s):
    """Parse a string into a dictionary."""
    #Fetch a *copy* of the default dictionary.
    ret = DEFAULTDICT.copy()
    #Split lines.
    lines = s.split("\n")
    #Loop through lines.
    for line in lines:
        #Strip whitespace.
        line = line.strip()
        #Skip comment and blank lines.
        if line and line[0] != "#":
            #Split the line in the pair key, value
            values = line.split()
            #Fill dictionary.
            ret[values[0]] = int(values[1])
    #Return dictionary.
    return ret

The above function is commented all the way so you should be able to
see what is going on.

With my best regards,
G. Rodrigues

More information about the Tutor mailing list