Python resources with properties file, update

2009 December 11
by DrSkippy27

The code I introduced in this post a few days ago has been evolving.  Below is the latest version.  Additions include searching multiple paths for the properties file, explicit naming of properties and minimal exception handling.  If you find this useful, please drop me a line in the comments.

#  $Date: 2009-12-07 19:11:09 -0700 (Mon, 07 Dec 2009) $
#  $Author: scott.hendrickson<at>buildingsi<dot>com $
#
##############################################
# Default resource files are named after class:
# class_name.properties
#
# If this class is the base class, then properties
# file is required.

import os, sys
import logging

class res:
    def __init__(self, logger=None,
                 resourceName=None):
        self.resourceValidFlag = False
        self.logger = logger
        self.resourceMap = {}
        # current path, path of script
        searchPaths = [os.getenv('PWD'),
                       sys.path[0]]
        if resourceName is None:
            filename = ''.join([self.__class__.__name__,
                                ".properties"])
        else:
            filename = ''.join([resourceName,
                                ".properties"])
        propFile = None
        for path in searchPaths:
            tmp = os.path.normpath(''.join([path,
                                            '/',
                                            filename]))
            if os.path.exists(tmp):
                propFile = tmp
        if propFile is not None:
            if self.logger is not None:
                self.logger.info("opening properties file %s" %
                                 filename)
            try:
                f = open(propFile, 'rb')
                for prop in f:
                    if prop[0] <> "#" and prop[0] <> '\n':
                        list = prop.split("=")
                        value = ''
                        for i in range(1,len(list)):
                            value += list[i] + "="
                        key = list[0]
                        value = value[:-1]
                        self.resourceMap[key] = value.strip("\n\r '\"").strip('\n\r')
                        if self.logger is not None:
                            self.logger.debug("property %s set to '%s'" %
                                              (key,
                                               self.resourceMap[key]))
                self.resourceValidFlag = True
            except IOError:
                if self.logger is not None:
                    self.logger.info("unable to read resource file %s" %
                                     propFile)
                else:
                    sys.stderr.write("unable to read resource file %s\n" %
                                     propFile)
        else:
            if self.logger is not None:
                self.logger.info("unable to find resource file %s in %s" %
                                 (filename,
                                  str(searchPaths)))
            else:
                sys.stderr.write("unable to find resource file %s in %s" %
                                 (filename,
                                  str(searchPaths)))

    def isValid(self):
        return self.resourceValidFlag

    def getString(self, key):
        if key in self.resourceMap:
            return self.resourceMap[key]
        else:
            if self.logger is not None:
                self.logger.error("resource %s missing" %
                                  key )
            else:
                sys.stderr.write("resource %s missing\n" %
                                 key )
        return None
No comments yet

Leave a Reply

You must be logged in to post a comment.