Skip to main content

Posts

Showing posts from June, 2008

More pyparsing and DHCP hosts

Since I wrote my original pyparsing post a few days ago, I've done some more work on refining my ISC dhcpd.conf host parsing example program. I also received some useful comments and suggests from Paul McGuire, the author the pyparsing module (thanks, Paul!), which I have also tried to incorporate. It's it's currently just a useless toy program but it is starting to look quite pretty. #!/usr/bin/python from pyparsing import * # An few host entries from dhcpd.conf sample_data = """ # A host with dynamic DNS attributes host a.foo.bar { ddns-hostname a; ddns-domainname "foo.bar"; hardware ethernet 00:11:22:33:44:55; fixed-address 192.168.100.10, 192.168.200.50; } # A simple multi-line host host b.foo.bar { hardware ethernet 00:0f:12:34:56:78; fixed-address 192.168.100.20; } # A simple single-line host host c.foo.bar { hardware ethernet 00:0e:12:34:50:70; fixed-address 192.168.100.40; } """ digits = "0123456789&qu

Recursive Descent Parsers and pyparsing

Yesterday while browsing the table of contents of the May 2008 issue of Python Magazine I came across a reference to the pyparsing module - a python module for writing recursive descent parsers using familiar python grammar. O'Reilly's Python DevCenter has an excellent introduction to using this module entitled Building Recursive Descent Parsers with Python . Well worth a read. It just so happens that I have a number of projects which are stalled because writing code to parse complexly structured data is not my strong point. I enjoy parsing up text line by line as much as the next guy but this recursive stuff I find tedious. The ISC DHCP configuration file is, in my opinion, a good example of parsing complexity. It's configuration directives can contain many optional directives, can be nested, and can be all on a single line or broken up move multiple lines. Writing the parser using pyparsing makes this much simpler. Here is a simple example of using pyparsing to parse