configParse.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #
  2. # configparse.py
  3. #
  4. # an example of using the parsing module to be able to process a .INI configuration file
  5. #
  6. # Copyright (c) 2003, Paul McGuire
  7. #
  8. from pyparsing import \
  9. Literal, Word, ZeroOrMore, Group, Dict, Optional, \
  10. printables, ParseException, restOfLine, empty
  11. import pprint
  12. inibnf = None
  13. def inifile_BNF():
  14. global inibnf
  15. if not inibnf:
  16. # punctuation
  17. lbrack = Literal("[").suppress()
  18. rbrack = Literal("]").suppress()
  19. equals = Literal("=").suppress()
  20. semi = Literal(";")
  21. comment = semi + Optional( restOfLine )
  22. nonrbrack = "".join( [ c for c in printables if c != "]" ] ) + " \t"
  23. nonequals = "".join( [ c for c in printables if c != "=" ] ) + " \t"
  24. sectionDef = lbrack + Word( nonrbrack ) + rbrack
  25. keyDef = ~lbrack + Word( nonequals ) + equals + empty + restOfLine
  26. # strip any leading or trailing blanks from key
  27. def stripKey(tokens):
  28. tokens[0] = tokens[0].strip()
  29. keyDef.setParseAction(stripKey)
  30. # using Dict will allow retrieval of named data fields as attributes of the parsed results
  31. inibnf = Dict( ZeroOrMore( Group( sectionDef + Dict( ZeroOrMore( Group( keyDef ) ) ) ) ) )
  32. inibnf.ignore( comment )
  33. return inibnf
  34. pp = pprint.PrettyPrinter(2)
  35. def test( strng ):
  36. print(strng)
  37. try:
  38. iniFile = open(strng)
  39. iniData = "".join( iniFile.readlines() )
  40. bnf = inifile_BNF()
  41. tokens = bnf.parseString( iniData )
  42. pp.pprint( tokens.asList() )
  43. except ParseException as err:
  44. print(err.line)
  45. print(" "*(err.column-1) + "^")
  46. print(err)
  47. iniFile.close()
  48. print()
  49. return tokens
  50. if __name__ == "__main__":
  51. ini = test("setup.ini")
  52. print("ini['Startup']['modemid'] =", ini['Startup']['modemid'])
  53. print("ini.Startup =", ini.Startup)
  54. print("ini.Startup.modemid =", ini.Startup.modemid)