snippets

Wednesday, June 01, 2005

Java like Property object written in Python - properties.py

I've been learning the python scripting language recently and decided to knock up a small script to kick off a daemon on my linux box.
I quickly got the script working, but it had a lot of hard coded values in it. I decided that I should use a properties file to initialise all those hard coded values as variables.
I wanted an object that behaved like the Java Property object that could be initialised from a property file and then queried in my script.
After a few days searching for such a thing I admitted defeat and decided to write my own, I was learning the language anyway so this could only help.

Python has a Map/Dictionary type object called a dictionary that you can create using the built-in function "dict()" I decided to extend it to have methods similar to Java's Properties object.

The following module - properties.py can be imported into a script and the Property object used to read a property file that ignors blank lines, lines begining with a "#" and leading white space on property names and values.

Properties are defined as "key value" pairs with the key and value being seperated with a ":" or a "=" character. A valid property file could look like:


# /var/tmp/testPropFile.properties file
# This is a sample
# properties file. lines
# begining with '#' are comments white space is ignored

propertyName1=value1
propertyName2 = value2
propertyName3 : value3

# this is a comment
#so is this
propertyName4:value4


The Property object could be used in a script like this:

#!/usr/bin/python
#
# test the properties.py module
#
from properties import Property

props = Property()
props.loadProperties("/var/tmp/testPropFile.properties")

for n, v in props.iteritems():
print n, " : ", v

print "the value of property propertyName3 is", props.getProperty("propertyName3")

props.setproperty("newKey","newkeyValue")

props.store("/var/tmp/testpropertyFile2.properties", "This is a test comment");
print "the value of name2 is ", props.getProperty("name2")
print "the value of newKeyis ", props.getProperty("newKey")



So here is my properties.py


#!/usr/bin/python
# Author: Karl Roberts
#
# python implementation of a Java Property object
#
# This file is in the public domain
# please feel free to use and edit it
# If you improove it please post a comment showing me how and I'll probably add
# it to this demo. cheers
#
import sys, os, string, re

class Property(dict):

#dict of properties
nvseppattern = re.compile("=|:")
__commentre = re.compile("^\s*#|^\s*\n")

def __init__(self,properties=None):
"constructor. can be created by passing in another properties object if you want"
if properties is not None:
self.update(properties)

def getProperty(self, key):
"Searches for the property with the specified key in this property list."
return self[key]

def list(self,out):
"Prints this property list out to the specified output stream. This method is useful for debugging."
return self.items()

def loadProperties(self,propsFileName):
"Reads a property list (key and element pairs) from the properties file"
#read the properties file defined in init
f = file(propsFileName)
pList = f.readlines()
#populate the dict with key value pairs (readline split on = or :
# need to strip the keys and values & remove \n
#wanted to do this with a generator majic but not got version 4 of python yet
#so do it with a loop.
i=0
l=len(pList)
while i < l:
if re.match(self.__commentre,pList[i]):
del(pList[i])
l=len(pList)
continue
i=i+1

mydic=dict([(l[0].strip(),l[1].strip()) for l in ([re.split(self.__nvseppattern,s,1) for s in pList])])
self.update(mydic)
return self

def propertyNames(self):
"Returns an iterator of all the keys in this property list, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list."
return self.iterkeys()

def setProperty(self, key, value):
"add a property to this object"
self.update({key: value})

def store(self, outputFileName, comment):
"Outputs the properties to a file in a manner that can be read with load(). comment is a comment added to the top of the file"
f = file(outputFileName, 'w+')
f.write("# "+comment+"\n");
for key, value in self.iteritems():
f.write(key+"="+value + "\n")
f.close()

#END of File



Cheers

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home