home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / CONFIGPARSER.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  16.9 KB  |  470 lines

  1. """Configuration file parser.
  2.  
  3. A setup file consists of sections, lead by a "[section]" header,
  4. and followed by "name: value" entries, with continuations and such in
  5. the style of RFC 822.
  6.  
  7. The option values can contain format strings which refer to other values in
  8. the same section, or values in a special [DEFAULT] section.
  9.  
  10. For example:
  11.  
  12.     something: %(dir)s/whatever
  13.  
  14. would resolve the "%(dir)s" to the value of dir.  All reference
  15. expansions are done late, on demand.
  16.  
  17. Intrinsic defaults can be specified by passing them into the
  18. ConfigParser constructor as a dictionary.
  19.  
  20. class:
  21.  
  22. ConfigParser -- responsible for for parsing a list of
  23.                 configuration files, and managing the parsed database.
  24.  
  25.     methods:
  26.  
  27.     __init__(defaults=None)
  28.         create the parser and specify a dictionary of intrinsic defaults.  The
  29.         keys must be strings, the values must be appropriate for %()s string
  30.         interpolation.  Note that `__name__' is always an intrinsic default;
  31.         it's value is the section's name.
  32.  
  33.     sections()
  34.         return all the configuration section names, sans DEFAULT
  35.  
  36.     has_section(section)
  37.         return whether the given section exists
  38.  
  39.     has_option(section, option)
  40.         return whether the given option exists in the given section
  41.  
  42.     options(section)
  43.         return list of configuration options for the named section
  44.  
  45.     has_option(section, option)
  46.         return whether the given section has the given option
  47.  
  48.     read(filenames)
  49.         read and parse the list of named configuration files, given by
  50.         name.  A single filename is also allowed.  Non-existing files
  51.         are ignored.
  52.  
  53.     readfp(fp, filename=None)
  54.         read and parse one configuration file, given as a file object.
  55.         The filename defaults to fp.name; it is only used in error
  56.         messages (if fp has no `name' attribute, the string `<???>' is used).
  57.  
  58.     get(section, option, raw=0, vars=None)
  59.         return a string value for the named option.  All % interpolations are
  60.         expanded in the return values, based on the defaults passed into the
  61.         constructor and the DEFAULT section.  Additional substitutions may be
  62.         provided using the `vars' argument, which must be a dictionary whose
  63.         contents override any pre-existing defaults.
  64.  
  65.     getint(section, options)
  66.         like get(), but convert value to an integer
  67.  
  68.     getfloat(section, options)
  69.         like get(), but convert value to a float
  70.  
  71.     getboolean(section, options)
  72.         like get(), but convert value to a boolean (currently defined as 0 or
  73.         1, only)
  74.  
  75.     remove_section(section)
  76.     remove the given file section and all its options
  77.  
  78.     remove_option(section, option)
  79.     remove the given option from the given section
  80.  
  81.     set(section, option, value)
  82.         set the given option
  83.  
  84.     write(fp)
  85.     write the configuration state in .ini format
  86. """
  87.  
  88. import sys
  89. import string
  90. import re
  91.  
  92. DEFAULTSECT = "DEFAULT"
  93.  
  94. MAX_INTERPOLATION_DEPTH = 10
  95.  
  96.  
  97.  
  98. # exception classes
  99. class Error:
  100.     def __init__(self, msg=''):
  101.         self._msg = msg
  102.     def __repr__(self):
  103.         return self._msg
  104.  
  105. class NoSectionError(Error):
  106.     def __init__(self, section):
  107.         Error.__init__(self, 'No section: %s' % section)
  108.         self.section = section
  109.  
  110. class DuplicateSectionError(Error):
  111.     def __init__(self, section):
  112.         Error.__init__(self, "Section %s already exists" % section)
  113.         self.section = section
  114.  
  115. class NoOptionError(Error):
  116.     def __init__(self, option, section):
  117.         Error.__init__(self, "No option `%s' in section: %s" %
  118.                        (option, section))
  119.         self.option = option
  120.         self.section = section
  121.  
  122. class InterpolationError(Error):
  123.     def __init__(self, reference, option, section, rawval):
  124.         Error.__init__(self,
  125.                        "Bad value substitution:\n"
  126.                        "\tsection: [%s]\n"
  127.                        "\toption : %s\n"
  128.                        "\tkey    : %s\n"
  129.                        "\trawval : %s\n"
  130.                        % (section, option, reference, rawval))
  131.         self.reference = reference
  132.         self.option = option
  133.         self.section = section
  134.  
  135. class InterpolationDepthError(Error):
  136.     def __init__(self, option, section, rawval):
  137.         Error.__init__(self,
  138.                        "Value interpolation too deeply recursive:\n"
  139.                        "\tsection: [%s]\n"
  140.                        "\toption : %s\n"
  141.                        "\trawval : %s\n"
  142.                        % (section, option, rawval))
  143.         self.option = option
  144.         self.section = section
  145.  
  146. class ParsingError(Error):
  147.     def __init__(self, filename):
  148.         Error.__init__(self, 'File contains parsing errors: %s' % filename)
  149.         self.filename = filename
  150.         self.errors = []
  151.  
  152.     def append(self, lineno, line):
  153.         self.errors.append((lineno, line))
  154.         self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)
  155.  
  156. class MissingSectionHeaderError(ParsingError):
  157.     def __init__(self, filename, lineno, line):
  158.         Error.__init__(
  159.             self,
  160.             'File contains no section headers.\nfile: %s, line: %d\n%s' %
  161.             (filename, lineno, line))
  162.         self.filename = filename
  163.         self.lineno = lineno
  164.         self.line = line
  165.  
  166.  
  167.  
  168. class ConfigParser:
  169.     def __init__(self, defaults=None):
  170.         self.__sections = {}
  171.         if defaults is None:
  172.             self.__defaults = {}
  173.         else:
  174.             self.__defaults = defaults
  175.  
  176.     def defaults(self):
  177.         return self.__defaults
  178.  
  179.     def sections(self):
  180.         """Return a list of section names, excluding [DEFAULT]"""
  181.         # self.__sections will never have [DEFAULT] in it
  182.         return self.__sections.keys()
  183.  
  184.     def add_section(self, section):
  185.         """Create a new section in the configuration.
  186.  
  187.         Raise DuplicateSectionError if a section by the specified name
  188.         already exists.
  189.         """
  190.         if self.__sections.has_key(section):
  191.             raise DuplicateSectionError(section)
  192.         self.__sections[section] = {}
  193.  
  194.     def has_section(self, section):
  195.         """Indicate whether the named section is present in the configuration.
  196.  
  197.         The DEFAULT section is not acknowledged.
  198.         """
  199.         return section in self.sections()
  200.  
  201.     def options(self, section):
  202.         """Return a list of option names for the given section name."""
  203.         try:
  204.             opts = self.__sections[section].copy()
  205.         except KeyError:
  206.             raise NoSectionError(section)
  207.         opts.update(self.__defaults)
  208.         if opts.has_key('__name__'):
  209.             del opts['__name__']
  210.         return opts.keys()
  211.  
  212.     def has_option(self, section, option):
  213.         """Return whether the given section has the given option."""
  214.         return option in self.options(section)
  215.  
  216.     def read(self, filenames):
  217.         """Read and parse a filename or a list of filenames.
  218.         
  219.         Files that cannot be opened are silently ignored; this is
  220.         designed so that you can specify a list of potential
  221.         configuration file locations (e.g. current directory, user's
  222.         home directory, systemwide directory), and all existing
  223.         configuration files in the list will be read.  A single
  224.         filename may also be given.
  225.         """
  226.         if type(filenames) in [type(''), type(u'')]:
  227.             filenames = [filenames]
  228.         for filename in filenames:
  229.             try:
  230.                 fp = open(filename)
  231.             except IOError:
  232.                 continue
  233.             self.__read(fp, filename)
  234.             fp.close()
  235.  
  236.     def readfp(self, fp, filename=None):
  237.         """Like read() but the argument must be a file-like object.
  238.  
  239.         The `fp' argument must have a `readline' method.  Optional
  240.         second argument is the `filename', which if not given, is
  241.         taken from fp.name.  If fp has no `name' attribute, `<???>' is
  242.         used.
  243.  
  244.         """
  245.         if filename is None:
  246.             try:
  247.                 filename = fp.name
  248.             except AttributeError:
  249.                 filename = '<???>'
  250.         self.__read(fp, filename)
  251.  
  252.     def get(self, section, option, raw=0, vars=None):
  253.         """Get an option value for a given section.
  254.  
  255.         All % interpolations are expanded in the return values, based on the
  256.         defaults passed into the constructor, unless the optional argument
  257.         `raw' is true.  Additional substitutions may be provided using the
  258.         `vars' argument, which must be a dictionary whose contents overrides
  259.         any pre-existing defaults.
  260.  
  261.         The section DEFAULT is special.
  262.         """
  263.         try:
  264.             sectdict = self.__sections[section].copy()
  265.         except KeyError:
  266.             if section == DEFAULTSECT:
  267.                 sectdict = {}
  268.             else:
  269.                 raise NoSectionError(section)
  270.         d = self.__defaults.copy()
  271.         d.update(sectdict)
  272.         # Update with the entry specific variables
  273.         if vars:
  274.             d.update(vars)
  275.         option = self.optionxform(option)
  276.         try:
  277.             rawval = d[option]
  278.         except KeyError:
  279.             raise NoOptionError(option, section)
  280.  
  281.         if raw:
  282.             return rawval
  283.  
  284.         # do the string interpolation
  285.         value = rawval                  # Make it a pretty variable name
  286.         depth = 0                       
  287.         while depth < 10:               # Loop through this until it's done
  288.             depth = depth + 1
  289.             if string.find(value, "%(") >= 0:
  290.                 try:
  291.                     value = value % d
  292.                 except KeyError, key:
  293.                     raise InterpolationError(key, option, section, rawval)
  294.             else:
  295.                 break
  296.         if value.find("%(") >= 0:
  297.             raise InterpolationDepthError(option, section, rawval)
  298.         return value
  299.     
  300.     def __get(self, section, conv, option):
  301.         return conv(self.get(section, option))
  302.  
  303.     def getint(self, section, option):
  304.         return self.__get(section, string.atoi, option)
  305.  
  306.     def getfloat(self, section, option):
  307.         return self.__get(section, string.atof, option)
  308.  
  309.     def getboolean(self, section, option):
  310.         v = self.get(section, option)
  311.         val = string.atoi(v)
  312.         if val not in (0, 1):
  313.             raise ValueError, 'Not a boolean: %s' % v
  314.         return val
  315.  
  316.     def optionxform(self, optionstr):
  317.         return string.lower(optionstr)
  318.  
  319.     def has_option(self, section, option):
  320.         """Check for the existence of a given option in a given section."""
  321.         if not section or section == "DEFAULT":
  322.             return self.__defaults.has_key(option)
  323.         elif not self.has_section(section):
  324.             return 0
  325.         else:
  326.             return self.__sections[section].has_key(option)
  327.  
  328.     def set(self, section, option, value):
  329.         """Set an option."""
  330.         if not section or section == "DEFAULT":
  331.             sectdict = self.__defaults
  332.         else:
  333.             try:
  334.                 sectdict = self.__sections[section]
  335.             except KeyError:
  336.                 raise NoSectionError(section)
  337.         sectdict[option] = value
  338.  
  339.     def write(self, fp):
  340.         """Write an .ini-format representation of the configuration state."""
  341.         if self.__defaults:
  342.             fp.write("[DEFAULT]\n")
  343.             for (key, value) in self.__defaults.items():
  344.                 fp.write("%s = %s\n" % (key, value))
  345.             fp.write("\n")
  346.         for section in self.sections():
  347.             fp.write("[" + section + "]\n")
  348.             sectdict = self.__sections[section]
  349.             for (key, value) in sectdict.items():
  350.                 if key == "__name__":
  351.                     continue
  352.                 fp.write("%s = %s\n" % (key, value))
  353.             fp.write("\n")
  354.  
  355.     def remove_option(self, section, option):
  356.         """Remove an option."""
  357.         if not section or section == "DEFAULT":
  358.             sectdict = self.__defaults
  359.         else:
  360.             try:
  361.                 sectdict = self.__sections[section]
  362.             except KeyError:
  363.                 raise NoSectionError(section)
  364.         existed = sectdict.has_key(key)
  365.         if existed:
  366.             del sectdict[key]
  367.         return existed
  368.  
  369.     def remove_section(self, section):
  370.         """Remove a file section."""
  371.         if self.__sections.has_key(section):
  372.             del self.__sections[section]
  373.             return 1
  374.         else:
  375.             return 0
  376.  
  377.     #
  378.     # Regular expressions for parsing section headers and options.  Note a
  379.     # slight semantic change from the previous version, because of the use
  380.     # of \w, _ is allowed in section header names.
  381.     SECTCRE = re.compile(
  382.         r'\['                                 # [
  383.         r'(?P<header>[-\w_.*,(){} ]+)'        # a lot of stuff found by IvL
  384.         r'\]'                                 # ]
  385.         )
  386.     OPTCRE = re.compile(
  387.         r'(?P<option>[-\w_.*,(){}]+)'         # a lot of stuff found by IvL
  388.         r'[ \t]*(?P<vi>[:=])[ \t]*'           # any number of space/tab,
  389.                                               # followed by separator
  390.                                               # (either : or =), followed
  391.                                               # by any # space/tab
  392.         r'(?P<value>.*)$'                     # everything up to eol
  393.         )
  394.  
  395.     def __read(self, fp, fpname):
  396.         """Parse a sectioned setup file.
  397.  
  398.         The sections in setup file contains a title line at the top,
  399.         indicated by a name in square brackets (`[]'), plus key/value
  400.         options lines, indicated by `name: value' format lines.
  401.         Continuation are represented by an embedded newline then
  402.         leading whitespace.  Blank lines, lines beginning with a '#',
  403.         and just about everything else is ignored.
  404.         """
  405.         cursect = None                            # None, or a dictionary
  406.         optname = None
  407.         lineno = 0
  408.         e = None                                  # None, or an exception
  409.         while 1:
  410.             line = fp.readline()
  411.             if not line:
  412.                 break
  413.             lineno = lineno + 1
  414.             # comment or blank line?
  415.             if string.strip(line) == '' or line[0] in '#;':
  416.                 continue
  417.             if string.lower(string.split(line)[0]) == 'rem' \
  418.                and line[0] in "rR":      # no leading whitespace
  419.                 continue
  420.             # continuation line?
  421.             if line[0] in ' \t' and cursect is not None and optname:
  422.                 value = string.strip(line)
  423.                 if value:
  424.                     cursect[optname] = cursect[optname] + '\n ' + value
  425.             # a section header or option header?
  426.             else:
  427.                 # is it a section header?
  428.                 mo = self.SECTCRE.match(line)
  429.                 if mo:
  430.                     sectname = mo.group('header')
  431.                     if self.__sections.has_key(sectname):
  432.                         cursect = self.__sections[sectname]
  433.                     elif sectname == DEFAULTSECT:
  434.                         cursect = self.__defaults
  435.                     else:
  436.                         cursect = {'__name__': sectname}
  437.                         self.__sections[sectname] = cursect
  438.                     # So sections can't start with a continuation line
  439.                     optname = None
  440.                 # no section header in the file?
  441.                 elif cursect is None:
  442.                     raise MissingSectionHeaderError(fpname, lineno, `line`)
  443.                 # an option line?
  444.                 else:
  445.                     mo = self.OPTCRE.match(line)
  446.                     if mo:
  447.                         optname, vi, optval = mo.group('option', 'vi', 'value')
  448.                         if vi in ('=', ':') and ';' in optval:
  449.                             # ';' is a comment delimiter only if it follows
  450.                             # a spacing character
  451.                             pos = string.find(optval, ';')
  452.                             if pos and optval[pos-1] in string.whitespace:
  453.                                 optval = optval[:pos]
  454.                         optval = string.strip(optval)
  455.                         # allow empty values
  456.                         if optval == '""':
  457.                             optval = ''
  458.                         cursect[self.optionxform(optname)] = optval
  459.                     else:
  460.                         # a non-fatal parsing error occurred.  set up the
  461.                         # exception but keep going. the exception will be
  462.                         # raised at the end of the file and will contain a
  463.                         # list of all bogus lines
  464.                         if not e:
  465.                             e = ParsingError(fpname)
  466.                         e.append(lineno, `line`)
  467.         # if any parsing errors occurred, raise an exception
  468.         if e:
  469.             raise e
  470.