.ini file parser (ConfigParser)

From: Ian Bicking (ianb_at_colorstudy.com)
Date: 10/22/04


Date: Thu, 21 Oct 2004 23:29:49 -0500
To: python-list@python.org

I've written a simple parser for .ini files; it's not a replacement for
ConfigParser, but you could build such a module ontop of it fairly
easily, or you could build something either more or less complicated.

svn://colorstudy.com/home/ianb/config/
http://colorstudy.com/cgi-bin/viewcvs.cgi/home/ianb/config/

For instance, here's the code to parse an ini file into a nested
dictionary, like {'section': {'var1': ['value1']}}:

class BasicParser(INIParser):

     def __init__(self):
         self.data = {}

     def assignment(self, name, content):
         if not self.section:
             self.parse_error(
                 'Assignments can only occur inside sections; no '
                 'section has been defined yet')
         section = self.data.setdefault(self.section, {})
         section.setdefault(name, []).append(content)

usage:

p = BasicParser()
p.feed('config.ini')
data = p.data

... though generally the parser should be a non-public implementation
detail in a config library. Anyway, not a lot of code, but I think it's
a good piece for building different config parsers. both simple and complex.

-- 
Ian Bicking  /  ianb@colorstudy.com  / http://blog.ianbicking.org


Relevant Pages

  • Re: Parse library
    ... this syntax is the config syntax used for Bind's config file ... > to comment the parser a bit better and throw it up as an article. ... > As you'll find out a compiler can go from one format to any other format, ... >> these tokens based on context. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Parse library
    ... Guess for now, will just leave as XML to get things working, then think ... > xsd.exe way and generate a config class that loads and writes out the ... or more interestingly a parser generator ... > generators out there, jay is just the one I happen to have used. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Read/write simple XML
    ... .NET uses .config files that are similar to INI files, ... Using the IDE, add a file called app.config to ... Kind of like an older app would read/write ...
    (microsoft.public.dotnet.framework)
  • Re: Parse library
    ... Then the parser assigns meaning to ... you would march the string and build a context ... If one was really nuts you could go the>> xsd.exe way and generate a config class that loads and writes out the> config ... There are a few other>> generators out there, jay is just the one I happen to have used. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Parse library
    ... sure, but if you aren't trying to compile to MSIL or anything, it'd be ... xsd.exe way and generate a config class that loads and writes out the config ... or more interestingly a parser generator based ... Its the parser generator that mono uses. ...
    (microsoft.public.dotnet.languages.csharp)