Added simple inifile-to-dictionary parser
parent
d635e83431
commit
4085039997
|
@ -0,0 +1,50 @@
|
||||||
|
try:
|
||||||
|
import configparser
|
||||||
|
except ImportError:
|
||||||
|
import ConfigParser as configparser
|
||||||
|
|
||||||
|
def read_config(filename):
|
||||||
|
'''Parse an ini file into a nested dictionary
|
||||||
|
|
||||||
|
:param string filename: Path to the ini file to read
|
||||||
|
:returns: A dictionary whose keys correspond to the section and
|
||||||
|
option, joined with a dot character (.)
|
||||||
|
|
||||||
|
For example, consider the following ini file::
|
||||||
|
|
||||||
|
[xmen]
|
||||||
|
storm = Ororo Monroe
|
||||||
|
cyclops = Scott Summers
|
||||||
|
|
||||||
|
[avengers]
|
||||||
|
hulk = Bruce Banner
|
||||||
|
iron_man = Tony Stark
|
||||||
|
|
||||||
|
The resulting dictionary would look like this::
|
||||||
|
|
||||||
|
{
|
||||||
|
'xmen.storm': 'Ororo Monroe',
|
||||||
|
'xmen.cyclops': 'Scott Summers',
|
||||||
|
'avengers.hulk': 'Bruce Banner',
|
||||||
|
'avengers.iron_man': 'Tony Stark',
|
||||||
|
}
|
||||||
|
|
||||||
|
Thus, the option values for any section can be obtained as follows::
|
||||||
|
|
||||||
|
config['xmen.storm']
|
||||||
|
|
||||||
|
This dictionary can be used to configure an :py:class:`~milla.Application`
|
||||||
|
instance by using the ``update`` method::
|
||||||
|
|
||||||
|
app = milla.Application(router)
|
||||||
|
app.config.update(config)
|
||||||
|
'''
|
||||||
|
|
||||||
|
cparser = configparser.SafeConfigParser()
|
||||||
|
cparser.readfp(open(filename))
|
||||||
|
|
||||||
|
config = {}
|
||||||
|
for section in cparser.sections():
|
||||||
|
for option in cparser.options(section):
|
||||||
|
config['.'.join((section, option))] = cparser.get(section, option)
|
||||||
|
return config
|
Loading…
Reference in New Issue