2017-11-08 2 views
0

에서 "확장"템플릿 기반의 INI 파일을 구문 분석 내가 구문 분석 (및 데이터베이스에 공급) 이와 같은 구성 파일을해야합니다 (실제로는 Asterisksip.conf입니다) :파이썬

[client-template](!,natted-template) 
foo=foovalue 
moo=moovalue 

[client](client-template) 
bar=barvalue 

이 구문 수단 그 client-templatenatted-template (다른 곳에서 정의 됨)을 기반으로하는 템플릿 자체입니다 (괄호 안은 !이기 때문에). clientclient-template을 기반으로 한 개체 정의입니다.

ConfigParser을 사용할 수는 있지만 더 강력하거나 사용자 정의 된 것이 필요합니까? 지금은 pyparsing을 시도했습니다

답변

0

음,이 (그리고이 모르고 지금까지 의견입니다) 솔루션의 일부입니다,하지만 난 그것을 진행할 수 있습니다

import pyparsing as pp 

filename = 'client.conf' 

nametag = pp.Word(pp.alphanums + "-_") 

variable = pp.Word(pp.alphanums) 
value = pp.Word(pp.alphanums + "=") 

vardef = pp.Group(variable('variable') + pp.Literal("=").suppress() + value('value')) 
vardefs = pp.Group(pp.ZeroOrMore(vardef))('vardefs') 

section = pp.Group(pp.Literal("[").suppress() \ 
     + nametag('objectname') \ 
     + pp.Literal("]").suppress() \ 
     + pp.Optional(
       pp.Literal("(").suppress() \ 
       + pp.Optional("!")('istemplate') 
       + pp.ZeroOrMore(pp.Optional(",").suppress() + nametag)('parenttemplates') \ 
       + pp.Literal(")").suppress() 
      ) \ 
     + vardefs) 

section = section + pp.Optional(pp.SkipTo(section)).suppress() 

section_group = pp.Group(section + pp.ZeroOrMore(section))('sections') 

config = (pp.SkipTo(section_group).suppress() \ 
     + section_group) 


# res = config.parseString(open(filename).read()) 

.

더 세련된 해결책이 있다면 알려주십시오.