救援用的欧芹!它似乎是编写自定义解析器的最简单的模块,并使用python对象生成结果,这些对象很容易转换回相同格式的配置文件。以下小方块的样品溶液:from parsley import makeGrammar, unwrapGrammar
from collections import OrderedDict
configFileGrammer = r"""
file = block+:bs end -> OrderedDict(bs)
block = ws name:b ws '{' ws members:m ws '}' ws -> (b, OrderedDict(m))
members = (setting:first (ws setting)*:rest ws -> [first] + rest) | -> []
setting = pair | flag
pair = ws name:k ws '=' ws name:v ws ';' ws -> (k, v)
flag = ws name:k ws ';' ws -> (k, True)
name = :n -> n.strip()
"""
testSource = r"""
portsbuild {
path = /jails/portsbuild;
allow.mount;
mount.devfs;
host.hostname = portsbuild.home;
ip4.addr = 192.168.0.200;
interface = nfe0;
exec.start = "/bin/sh /etc/rc";
exec.stop = "/bin/sh /etc/rc.shutdown";
}
web01 {
path = /jails/web01;
allow.mount;
mount.devfs;
host.hostname = web02.site.com;
ip4.addr = 10.0.0.1;
interface = eth0;
exec.start = "/bin/sh /etc/rc";
}
db01 {
path = /jails/db01;
mount.devfs;
host.hostname = db01.home;
ip4.addr = 192.168.6.66;
interface = if0;
exec.start = "/bin/mysql";
}
"""
ConfigFile = makeGrammar(configFileGrammer, globals(), name="ConfigFile")
config = unwrapGrammar(ConfigFile)(testSource).apply('file')[0]
for block in config:
print "%s {" % block
for key in config[block]:
if config[block][key] == True:
print "\t%s;" % key
else:
print "\t%s = %s;" % (key, config[block][key])
print "}"