#!/usr/bin/python
#-*- coding: utf-8 -*-
#
# configparse.py
#
# an example of using the parsing module to be able to process a .INI configuration file
#
# Copyright (c) 2003, Paul McGuire
#

from pyparsing import Literal, Word, ZeroOrMore, Group, Dict, Optional, \
        printables, ParseException, restOfLine
import os

def inifile_BNF():
	# punctuation
	lbrack = Literal("[").suppress()	# erscheint nicht in der Ausgabe
	rbrack = Literal("]").suppress()
	equals = Literal("=").suppress()
	fence  = Literal("#")
	
	comment = fence + Optional( restOfLine )
	
	nonrbrack = "".join( [ c for c in printables if c != "]" ] ) + " \täöüßÄÖÜ"
	nonequals = "".join( [ c for c in printables if c != "=" ] ) + " \täöüßÄÖÜ"
	
	sectionDef = lbrack + Word( nonrbrack ) + rbrack
	keyDef = ~lbrack + Word( nonequals ) + equals + restOfLine
	
	# using Dict will allow retrieval of named data fields as attributes of the parsed results
	inibnf = Dict( ZeroOrMore( Group( sectionDef + Dict( ZeroOrMore( Group( keyDef ) ) ) ) ) )
	
	inibnf.ignore( comment )

	return inibnf


def test( strng ):
	bnf = inifile_BNF()
	tokens = bnf.parseString(strng)
	return tokens

def main():
	input = """
[INIT]   # Kommentar
var1=Test
vär2=34
var3=23.45
[Application]
start=1
dir=/home/vt4/ma
"""

	ini = test(input)
	for item in ini:
		print item

	print 'Wert von INIT/var3 = ', ini['INIT']['var3']

main()
