My current project reads a lot of data from multiple .ini files, and needs to have more than one accessible at a time. I have put together this class to handle the ini-reading, and I thought it might have broader utility for Panda users. Note that the code is derived from a Panda example (apparently incomplete and not linked as a dowload), found here: http://code.google.com/p/python-panda3d-examples/
class iniReader(object):
"""
Modified from:
http://code.google.com/p/python-panda3d-examples/
Functions to load and read configuration from an ini file.
import ConfigParser # For the .ini reader
Class object to read and store multiple ini files.
Use:
self.ini = iniReader()
self.ini.load(os.path.join(self.paths.dirname, self.paths.settings),"settings")
self.ini.set_current("settings")
numcastles = self.ini.readInteger("castles", "count", 5)
"""
def __init__(self):
self.current_ini = None
def load(self, ini_path, name):
"""Load submitted ini at path to __dict__, using name (string) as key"""
config_parser = ConfigParser.ConfigParser()
self.__dict__[name] = {}
self.current_ini = self.__dict__[name]
config_parser.read(ini_path)
for section in config_parser.sections():
self.current_ini[section] = {}
for option in config_parser.options(section):
self.current_ini[section][option] = config_parser.get(section, option)
def __getitem__(self, name):
return self.__dict__[name]
def set_current(self, name):
"""Set the current ini dict to read, by name (string)"""
if name in self.__dict__:
self.current_ini = self.__dict__[name]
def has_section(self, section):
"""Verify that current ini dict has a key for submitted selection"""
if section in self.current_ini.keys():
return True
return False
def readString(self, section, option, default):
"""Return ini data from dict as string, with default"""
try:
return str(self.current_ini[section][option])
except KeyError:
return default
def readInteger(self, section, option, default):
"""Return ini data from dict as integer, with default"""
try:
return int(self.current_ini[section][option])
except KeyError:
return default
def readFloat(self, section, option, default):
"""Return ini data from dict as float, with default"""
try:
return float(self.current_ini[section][option])
except KeyError:
return default
def clear(self, name):
"""Clear the ini listing with the submitted name (string)"""
if name in self.__dict__:
if self.__dict__[name] == self.current_ini:
self.current_ini = None
self.__dict__[name] = None
del self.__dict__[name]