在python中解析groovy文件 [英] Parsing a groovy file in python

查看:306
本文介绍了在python中解析groovy文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a groovy config file that I want to append data too. It would be easier to gather data using python that I want to add but I couldn't find a corresponding ConfigSlurper module in python and there is no straightforward way I saw to be able to do this using ConfigParser or anything. Has anyone done anything like this that has some feedback/advice on best approach?

推荐答案

那是一个有趣的练习.

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'}}

这篇关于在python中解析groovy文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆