Skip to content

Instantly share code, notes, and snippets.

@jianingy
Created June 15, 2013 14:10
Show Gist options
  • Save jianingy/5788275 to your computer and use it in GitHub Desktop.
Save jianingy/5788275 to your computer and use it in GitHub Desktop.
a sample for parsing a nginx-like conf
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# filename : ustack.py
# created at : 2013-06-15 21:05:10
# author : Jianing Yang <jianingy.yang AT gmail DOT com>
__author__ = 'Jianing Yang <jianingy.yang AT gmail DOT com>'
from pyparsing import *
import sys
BUILTIN_VARS = dict(total_instance=200)
def load_variable(*fns, **kwargs):
token = fns[-1][0][1:]
if token not in BUILTIN_VARS:
print >>sys.stderr, "Unknown variable: %s!" % token
return ""
return BUILTIN_VARS[token]
def parse(input):
LBRACE, RBRACE, SEMI, QUOTE = map(Suppress, '{};"')
LPAREN, RPAREN = map(Suppress, '()')
string = (QuotedString('"', "\\") | QuotedString("'", "\\") |
Word(alphanums + "_-"))
number = Combine(Optional('-') + ('0' | Word('123456789', nums)) +
Optional('.' + Word(nums)))
ident = Word(alphanums + "_")
var = Combine(Word("$") + ident).setParseAction(load_variable)
fun = ident + LPAREN + RPAREN
value = (string | number | var | fun)
simple_stmt = ident.setResultsName("key") + \
value.setResultsName("value") + SEMI
stmt = simple_stmt
section = ident.setResultsName("section") + \
LBRACE + Dict(ZeroOrMore(Group(stmt))).setResultsName("stmt") + RBRACE
for recipe in section.searchString(input):
print "section =", recipe.section
for stmt in recipe.stmt:
print " ", stmt.key, "=", stmt.value
return True
case = """service {
name 'mysql';
instance $total_instance;
}
application {
service mysql;
service apache;
}
"""
print parse(case)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment