1

I have a non-standard configuration file, for which I want to write a python parser.

What is the best approach to writing a parser from scratch?

Example of a configuration file:

// Comment 
conf OPTION_NAME {
     (
       ( option1:"string"
         option2:"14"
       )
     )
}


// Comment2 
conf OPTION_NAME2 {
     (
       ( option1:"string2"
         option2:"15"
       )
     )
}
HerbSpiral
  • 183
  • 1
  • 2
  • 8
  • 1
    Is the format of the configuration file under your control? – Sven Marnach Feb 27 '12 at 15:28
  • Unfortunately, no , it's a legacy file, not under my control. But this is a good exercise for any non-standard conf file/code. – HerbSpiral Feb 27 '12 at 15:29
  • There's not enough information here. What is the grammar of this language? – David Heffernan Feb 27 '12 at 15:31
  • 1
    Write a BNF grammar first, (if you can't change the config so you can). Perhaps this SO post might help. http://stackoverflow.com/questions/264262/grammar-writing-tools – Tony Hopkinson Feb 27 '12 at 15:32
  • I would say that this really depends on how flexible your format is. For instance, I don't see the point of the double nesting inside your options unless it allows for constructions you didn't tell us of. – jena Feb 27 '12 at 15:33
  • 2
    I've used [`PyParsing`](http://pyparsing.wikispaces.com/) the few times I've had to write a parser in Python. The first thing you should do is write down the grammar of your language. – Katriel Feb 27 '12 at 15:48

1 Answers1

2

I would personally use PLY: http://www.dabeaz.com/ply/

Here's a simple example:

http://www.dabeaz.com/ply/example.html

Here's an example from one of my own projects:

https://github.com/fogleman/FeedNotifier/blob/master/filters.py

Alternatively, since the files look very simple, I might just use a handmade Finite State Machine to do the parsing.

FogleBird
  • 74,300
  • 25
  • 125
  • 131