在python中解析groovy文件

我有一个普通的配置文件,我也想附加数据.使用我想添加的python收集数据会更容易,但是我无法在python中找到相应的ConfigSlurper模块,而且我没有简单的方法可以使用ConfigParser或其他任何方法来做到这一点.有没有人做过这样的事情,对最佳方法有一些反馈/建议?

解决方法:

那是一个有趣的练习.

from shlex import shlex
from ast import literal_eval

TRANSLATION = {
        "true": True,
        "false": False,
        "null": None,
    }

class ParseException(Exception):
    def __init__(self, token, line):
        self.token = token
        self.line = line
    def __str__(self):
        return "ParseException at line %d: invalid token %s" % (self.line, self.token)

class GroovyConfigSlurper:
    def __init__(self, source):
        self.source = source

    def parse(self):
        lex = shlex(self.source)
        lex.wordchars += "."
        state = 1
        context = []
        result = dict()
        while 1:
            token = lex.get_token()
            if not token:
                return result
            if state == 1:
                if token == "}":
                    if len(context):
                        context.pop()
                    else:
                        raise ParseException(token, lex.lineno)
                else:
                    name = token
                    state = 2
            elif state == 2:
                if token == "=":
                    state = 3
                elif token == "{":
                    context.append(name)
                    state = 1
                else:
                    raise ParseException(token, lex.lineno)
            elif state == 3:
                try:
                    value = TRANSLATION[token]
                except KeyError:
                    value = literal_eval(token)
                key = ".".join(context + [name]).split(".")
                current = result
                for i in xrange(0, len(key) - 1):
                    if key[i] not in current:
                        current[key[i]] = dict()
                    current = current[key[i]]
                current[key[-1]] = value
                state = 1

那你就可以

with open("test.conf", "r") as f:
    print GroovyConfigSlurper(f).parse()
# => {'setting': {'smtp': {'mail': {'host': 'smtp.myisp.com', 'auth': {'user': 'server'}}}}, 'grails': {'webflow': {'stateless': True}}, 'resources': {'URL': 'http://localhost:80/resources'}}
上一篇:基于IntelliJ IDEA创建第一个Groovy工程


下一篇:菜鸟学数据库(六)——方便快捷的开启、关闭Oracle服务