1

我需要解析一个配置文件文件,以便能够添加/删除/修改软件配置,该配置由多个格式的文本块定义,如下所示:

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";
}

这些块是相当重复的,到目前为止,只有变量的值在变化。

我尝试过使用该re模块,但最终得到的代码过于臃肿和复杂。然后我尝试了该iscpy模块,代码非常简单(一行将整个文件转换为方便的字典),但解析的数据并不完全是它应该是的:

>>> conf = iscpy.ParseISCString(open('/etc/jail.conf', 'r').read())
>>> conf
{'portsbuild': {'allow.mount': True, 'interface = nfe0': True, 'exec.start = "/bin/sh /etc/rc"': True, 'ip4.addr': '= 192.168.0.200', 'exec.stop': '= "/bin/sh /etc/rc.shutdown"', 'exec.stop = "/bin/sh /etc/rc.shutdown"': True, 'ip4.addr = 192.168.0.200': True, 'path': '= /jails/portsbuild', 'interface': '= nfe0', 'path = /jails/portsbuild': True, 'mount.devfs': True, 'host.hostname': '= portsbuild.home', 'host.hostname = portsbuild.home': True, 'exec.start': '= "/bin/sh /etc/rc"'}}

我也试过我的运气,pyparsing但它似乎只适合一种方式。所以,我想知道是否有其他模块或方法可以使用干净且易于理解的代码来解析该文件,这两种方式都可以使用,用于在修改 python 对象后读取和写入?

4

1 回答 1

2

欧芹救命!似乎它是编写自定义解析器的最简单模块,并使用 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 = <(~('='|';'|'{') anything)+>: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 "}"
于 2013-03-28T09:42:40.317 回答