将文本文件内容解析为Python对象并将对象写回可解析文本fi

2024-10-02 22:27:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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模块,代码非常简单(只需一行代码就可以将整个文件转换成一个方便的字典),但是解析的数据并不是它应该的那样:

^{pr2}$

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


Tags: 模块文件方法代码文本bin软件定义
1条回答
网友
1楼 · 发布于 2024-10-02 22:27:13

救援用的欧芹!它似乎是编写自定义解析器的最简单的模块,并使用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 "}"

相关问题 更多 >