Config class in Python

#!/usr/bin/python
#
# =======================================================================
# Config.py : Python config class to handle configurations
#
# methods: Config() - constructor
#          modName() - return modulename
#		   show() - show = debug function
#          setValue() - set the config value
#          getValue() - get config value
#          getKeys() - return all keys
#          read() - read config values from file
# =======================================================================
#

import os
import sys
import ConfigParser
import logging

class Config:
	
	# class vars
	className = 'Config'
	logger = logging.getLogger(className)
	moduleName = 'Config'
	keyArray = [
		'defaultPath',
		'logConfig',
		'progConfig'
	]
	values = { }
	
	def __init__(self):
		logging.basicConfig()
		self.logger = logging.getLogger(self.className)
		self.logger.info('__init__')
		print self.keyArray
		defaultValue = 'undef'
		for k in self.keyArray:
			self.values[k] = defaultValue

	def modName(self):
		return self.moduleName
		
	def show(self):
		print self.keyArray
		print self.values
		
	def setValue(self, k, v):
		self.values[k] = v
		
	def getValue(self, k):
		return self.values[k]
		
	def getKeys(self):
		return self.keyArray
		
	def read(self, filename):
		if os.path.exists(filename):
			cp = ConfigParser.ConfigParser()
			try:
				all = cp.read(filename)
				items = cp.items('Config')
				#print items
				for k in self.keyArray:
					print k,'=',cp.get(self.moduleName, k)
					self.values[k] = cp.get(self.moduleName, k)
			except:
				print "*ERROR* - Unable to read "+filename
			
# main
if __name__ == "__main__":	# if main
	print "main"
	cfg = Config()
	cfg.show()
	cfg.read('tl.ini')
	cfg.show()
	

Config file

[Config]
defaultPath = c:\temp
logConfig = log.ini
progConfig = tl.ini

* Back to Python

pyconfig.txt · Last modified: 2014/10/26 01:52 (external edit)
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0