3

我有一个 groovy 配置文件,我也想附加数据。使用我想添加的 python 收集数据会更容易,但我在 python 中找不到相应的 ConfigSlurper 模块,而且我看到没有直接的方法可以使用 ConfigParser 或任何东西来做到这一点。有没有人做过这样的事情,对最佳方法有一些反馈/建议?

4

1 回答 1

6

那是一个有趣的练习。

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'}}
于 2015-08-26T02:31:27.197 回答