Python parsing an ugly configuration file
<p>I have an application generating a weird config file</p>

<pre><code>app_id1 {
key1 = val
key2 = val
...
}
app_id2 {
key1 = val
key2 = val
...
}
...
</code></pre>

<p>And I am struggling on how to parse this in python. The keys of each app may vary too.
I can't change the application to generate the configuration file in some easily parsable format :)</p>

<p>Any suggestions on how to do this pythonically ?
I am thinking along the lines of dict of dict</p>

<pre><code>conf = {'app_id1': {'key1' : 'val', 'key2' : 'val'},
        'app_id2' : {'key1' : 'val', 'key2' : 'val'}
       }
</code></pre>

<p>You can use <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing</a> for less strict grammar:</p>

<pre><code>from pyparsing import alphanums, restOfLine, OneOrMore, Word, Suppress
from copy import copy
lbrace,rbrace,eq = map(Suppress,"{}=")

configitem = {}
configall = {}

wd = Word(alphanums+'_')
kw = wd + eq + restOfLine
kw.setParseAction(lambda x: configitem.__setitem__(x[0],x[1].strip()))
group = wd + lbrace + OneOrMore(kw) + rbrace
group.addParseAction(lambda x: configall.__setitem__(x[0],copy(configitem)))
group.addParseAction(lambda x: configitem.clear())

config = OneOrMore(group)


config_file_string = '''app_id1 
{
key1 = val
key2 = val

key3 = val
}


app_id2 {
key1 = val

key2 = val

}'''

config.parseString(config_file_string)
print(configall)
</code></pre>

python parsing