Wednesday, September 30, 2009

Python - using yaml for configuration files

import yaml
# checkout and download yaml for python 

# you should probably put this config in a seperate file
# but for this example it is just a multi-line string
yamlConfigFile = """
cars:
    car0:
        type: toyota
        hp: 129
        mpg:
            city: 30
            highway: 35
        cost: 15,000
    car1:
        type: gm
        hp: 225
        mpg:
            city: 20
            highway: 25
        cost: 20,000
    car2:
        type: chevy
        hp: 220
        mpg:
            city: 22
            highway: 24
        cost: 21,000
"""

# the yaml file will be converted to a dict
# for sub sections the dict will nest dicts
theDict = yaml.load(yamlConfigFile)
print theDict
# output (I added some tabs and what not so you
#           could see the nested dict structure):
# {'cars':
#    {'car2':
#        {'mpg': {'city': 22, 'highway': 24},
#        'hp': 220,
#        'cost': '21,000',
#        'type': 'chevy'},
#    'car0':
#        {'mpg': {'city': 30, 'highway': 35},
#        'hp': 129,
#        'cost': '15,000',
#        'type': 'toyota'},
#    'car1':
#        {'mpg': {'city': 20, 'highway': 25},
#        'hp': 225,
#        'cost': '20,000',
#        'type': 'gm'}
#    }
#}

# to list the car types (like car1, car2, etc
print theDict['cars'].keys()
# output:
# ['car2', 'car0', 'car1']

# to display the type and cost of the vehicles
for c in theDict['cars'].keys():
    print theDict['cars'][c]['type'], "cost:", theDict['cars'][c]['cost']

# output:
#    chevy cost: 21,000
#    toyota cost: 15,000
#    gm cost: 20,000

# update the cost of toyota
theDict['cars']['car0']['cost'] = '25,000'
# the update is now in the dict representation of the yaml file

# to dump the yaml dict back to a file
# or in our case a multi-line string use the dump command
# which you could write to a file
print yaml.dump(theDict)
# output:
#    cars:
#      car0:
#        cost: 25,000
#        hp: 129
#        mpg: {city: 30, highway: 35}
#        type: toyota
#      car1:
#        cost: 20,000
#        hp: 225
#        mpg: {city: 20, highway: 25}
#        type: gm
#      car2:
#        cost: 21,000
#        hp: 220
#        mpg: {city: 22, highway: 24}
#        type: chevy



No comments:

Post a Comment