parser.py :  » Network » FtpCube » ftpcube-0.5.1 » libftpcube » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Network » FtpCube 
FtpCube » ftpcube 0.5.1 » libftpcube » parser.py
"""
FtpCube
Copyright (C) Michael Gilfix

This file is part of FtpCube.

You should have received a file COPYING containing license terms
along with this program; if not, write to Michael Gilfix
(mgilfix@eecs.tufts.edu) for a copy.

This version of FtpCube is open source; you can redistribute it and/or
modify it under the terms listed in the file COPYING.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
"""

import utils

import os
import exceptions
import ConfigParser

class ParserError(exceptions.RuntimeError):
    """Configuration parsing error exception."""

    def __init__(self, args=None):
        self.args = args

class SimpleConfigParser:
    """Simple configuration file parser base class.

    A simple configuration file parser is a parser for an INI style configuration
    file that contains only one section. All configuration parameters are treated
    as a dictionary. Each config parser takes a dictionary of configuration options,
    which are written to the single section as attribute/value pairs. A simple
    approach is taken to serialization using repr() and eval()."""

    def __init__(self, config_file, section_header, load_initial=True):
        """Creates a new configuration parser instance.

        If the specified config_file does not exist, then it is created. If the
        containing directory does not exist, it is also created. If 'load_initial'
        is False, then the bookmark has an empty dictionary and is not initialized
        until a call to load."""
        if config_file is None or not utils.isStrOrUnicode(config_file):
            raise ValueError, "config_file: %s" %config_file
        if section_header is None or not utils.isStrOrUnicode(section_header):
            raise ValueError, "section_header: %s" %section_header
        self.config_file = config_file
        self.section_header = section_header
        self.config = { }

        config_dir = os.path.dirname(self.config_file)
        if not os.path.exists(config_dir):
            try:
                os.mkdir(config_dir)
                os.chmod(config_dir, 0700)
            except OSError, strerror:
                raise ParserError(strerror)

        if load_initial:
            if not os.path.exists(self.config_file):
                defaults = self.getDefaults()
                self.config.update(defaults)
                self.save()
            else:
                cfg = self.load()

    def getDefaults(self):
        """Returns a dictionary of default values.

        This should be overridden by the implementing class to provide a default
        dictionary for auto-population of values."""
        return { }

    def __getitem__(self, item):
        """Gets a configuration value.

        The value returned reflects the in-memory configuration value and may be
        different from the value in the file until the next time the file is saved.
        If the specified configuration property does not exist, then a ParserError
        exception will be raised."""
        try:
            return self.config[item]
        except KeyError, strerror:
            raise ParserError(_("Invalid configuration option: %(opt)s")
                %{ 'opt' : strerror })

    def __setitem__(self, item, value):
        """Sets a configuration value.

        The value set is kept in-memory until the next time the configuration is
        saved."""
        self.config[item] = value
        return value

    def has_key(self, key):
        """Returns true if the configuration key is defined."""
        return self.config.has_key(key)

    def getPath(self):
        """Returns the path of the configuration file."""
        return self.config_file

    def getOptions(self):
        """Returns a dictionary containing all configuration options."""
        return self.config

    def setOptions(self, dict):
        """Sets all options to match the supplied dictionary."""
        self.config = dict

    def save(self):
        """Writes out an updated configuration file from the in-memory configuration
        dictionary."""
        if __debug__:
            print "Saving config file: %s" %self.config_file
        file = open(self.config_file, 'w')
        try:
            parser = ConfigParser.SafeConfigParser()
            parser.add_section(self.section_header)
            for key in self.config.keys():
                value = repr(self[key])
                parser.set(self.section_header, key, value)
            parser.write(file)
        finally:
            try:
                file.close()
            except Exception:
                pass

    def load(self):
        """Reads in a configuration file and populates the configuration dictionary."""
        if __debug__:
            print "Loading config file: %s" %self.config_file
        file = open(self.config_file, 'r')
        try:
            parser = ConfigParser.SafeConfigParser()
            parser.readfp(file, self.config_file)
            for key, value in parser.items(self.section_header):
                self[key] = eval(value)
        finally:
            try:
                file.close()
            except Exception:
                pass
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.