DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Python Config File Parser

09.05.2009
| 2880 views |
  • submit to reddit
        // description of your code here

from ConfigParser import SafeConfigParser,Error as CP_Error
from mwdb.exceptions import *
class MWDBConfig:
	def init(self,path):
		self._conf=None
		try:
			self._conf=SafeConfigParser()
			self._conf.readfp(open(path))
		except:
			self._conf=None
			raise ConfigException("load config file from:%s failed"%path)
	def _assert_conf(self):
		if self._conf == None:
			raise ConfigException("config is not initialized")

	def get(self,Sec,Key):
		self._assert_conf()
		try:
			return self._conf.get(Sec,Key)
		except CP_Error, e:
			raise ConfigException(e.message)
		except Exception,e: 
			raise ConfigException('get %s of %s with error:'%(Key,Sec,e.message))

	def get_int(self,Sec,Key):
		self._assert_conf()
		try:
			return self._conf.getint(Sec,Key)
		except CP_Error,e:
			raise ConfigException(e.message)
		except ValueError:
			raise ConfigException('%s of %s is not a integer'%(Key,Sec))
		except Exception,e: 
			raise ConfigException('get %s of %s with error:'%(Key,Sec,e.message))