0

I need to parse (and feed to a database) configuration files like this one (actually it is Asterisk's sip.conf):

[client-template](!,natted-template)
foo=foovalue
moo=moovalue

[client](client-template)
bar=barvalue

This syntax means that client-template is a template itself (because of ! in parentheses) based on natted-template (defined elsewhere). And client is an object definition, based on client-template.

I could use ConfigParser, but it looks like I need something more powerful or customized?

brownian
  • 435
  • 3
  • 13

1 Answers1

0

Well, now I've tried pyparsing:

import pyparsing as pp

filename = 'client.conf'

nametag = pp.Word(pp.alphanums + "-_")

variable = pp.Word(pp.alphanums)
value = pp.Word(pp.alphanums + "=")

vardef = pp.Group(variable('variable') + pp.Literal("=").suppress() + value('value'))
vardefs = pp.Group(pp.ZeroOrMore(vardef))('vardefs')

section = pp.Group(pp.Literal("[").suppress() \
        + nametag('objectname') \
        + pp.Literal("]").suppress() \
        + pp.Optional(
                pp.Literal("(").suppress() \
                + pp.Optional("!")('istemplate')
                + pp.ZeroOrMore(pp.Optional(",").suppress() + nametag)('parenttemplates') \
                + pp.Literal(")").suppress()
            ) \
        + vardefs)

section = section + pp.Optional(pp.SkipTo(section)).suppress()

section_group = pp.Group(section + pp.ZeroOrMore(section))('sections')

config = (pp.SkipTo(section_group).suppress() \
        + section_group)


# res = config.parseString(open(filename).read())

This is a part of a solution (and this is comments unaware so far), but I can proceed with it.

Please, if there is more elegant solution, let me know.

brownian
  • 435
  • 3
  • 13