Created
June 15, 2013 14:10
-
-
Save jianingy/5788275 to your computer and use it in GitHub Desktop.
a sample for parsing a nginx-like conf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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