Many people use Python modules as config files, but this way your program may be manipulated or an syntax error may come into that file. Try the small script here to use the good old INI config files, known from Windows.
| Python |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import ConfigParser
import string
_ConfigDefault = {
"database.dbms": "mysql",
"database.name": "",
"database.user": "root",
"database.password": "",
"database.host": "127.0.0.1"
}
def LoadConfig(file, config={}):
"""
returns a dictionary with key's of the form
<section>.<option> and the values
"""
config = config.copy()
cp = ConfigParser.ConfigParser()
cp.read(file)
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)
|
Discussion
This solution is just for reading config files. A write should be easy to be implemented. An INI file looks like this: <pre> [database] user = dummy password = tosca123 </pre> The defaults may be set in advance. The keys of the dictionary are always lower case, that helps ;-)


Comments
the writer... At first I saw this and said, "why concatenate the section and option?" seems like extra string processing right? it makes the write function harder i think. but once you get your dictionary, the values are easy to reference in your code.
here's the write function. i'm a newbie so it's probably not very tight code.
An updated a tighter write(). This updates the write() function for python > 2.4 and makes it tighter and a little easier to understand.
Also, sets eliminate the need for uniquer().
Sign in to comment