ConfigParser

Ivo Woltring Python at IvoNet.nl
Wed Nov 10 15:04:55 EST 2004


On Wed, 10 Nov 2004 10:39:27 GMT, Manlio Perillo
<NOmanlio_perilloSPAM at libero.it> wrote:

>Regards.
>
>Since sections in CongiParser files are delimited by [ and ], why
>there is not an escape (and unescape) function for escaping
>&, [, and ] characters to &, [ and ] ?
>
>
>
>
>Thanks   Manlio Perillo

By the way I did some testing because i have a similar thing going on
right now. I found out that

[section]
option = [Ivo Woltring]

is valid and does not have to be translated to
[section]
option = [Ivo Woltring]

to work.


so my current class is a bit unnessesary:

#
# IniFile extents the ConfigParser with my own functions
#
__author__    = "Ivo Woltring"
__version__   = "01.00"
__copyright__ = "Copyright (c) 2004 Ivo Woltring"
__license__   = "Python"

from ConfigParser import *

class IniFile(ConfigParser):
  """IniFile
  Is an extention on the ConfigParser class.
  It overrulles the write method so it can write directly to a file
provided as
  a parameter. The whole filehandling is done by the IniFile.write(fp)
method.
  """
  def __init__(self, defaults=None):
    ConfigParser.__init__(self, defaults) # supers init
    self.replace = [('[','['),
                    (']',']'),
                   ]
    
  def write(self,fp):
    """write(filename) --> written file"""
    try:
      f = open(fp,'w')
    except IOError:
      raise IOError
    #ConfigParser.write(self,f)
    self._write(f)
    f.close()
    
  def _replace(self, txt ,reverse=False):
    """Replace the self.replace stuff"""
    for source, target in self.replace:
      if reverse: txt=txt.replace(target, source)
      else:       txt=txt.replace(source, target)
    return txt
    
  def get(self, section, option, raw=False, vars=None):    # override
the get() method of super
    """get(section, option, [raw=False], [vars=None]) --> String
    this get() is an extention on the origional ConfigParser.get()
    This one translates html style '[' to '[' etc.
    """
    if raw:
      return ConfigParser.get(self, section, option, raw, vars) # call
the get of super
    return self._replace(ConfigParser.get(self, section, option, raw,
vars)) 
  
  def _write(self, fp):
      """Write an .ini-format representation of the configuration
state."""
      if self._defaults:
          fp.write("[%s]\n" % DEFAULTSECT)
          for (key, value) in self._defaults.items():
              fp.write("%s = %s\n" %
                       (key, self._replace(str(value).replace('\n',
'\n\t'), reverse=True)))
          fp.write("\n")
      for section in self._sections:
          fp.write("[%s]\n" % section)
          for (key, value) in self._sections[section].items():
              if key != "__name__":
                  fp.write("%s = %s\n" %
                           (key,
self._replace(str(value).replace('\n', '\n\t'), reverse=True)))
          fp.write("\n")



if __name__=="__main__":
  import sys,os
  p = IniFile()
  p.add_section('section')
  p.set('section','option','[Ivo Woltring]')
  p.write(os.path.splitext(sys.argv[0])[0]+'.ini')
  print p.get('section','option')
  print p.get('section','option', raw=True)
  raw_input('Press enter to continue...')  


have fun... I do,

Cheerz, Ivo.




More information about the Python-list mailing list