I'm trying to import a module that checks an .ini config file for correct syntax (via regex patterns). If the syntax is wrong, I want the main code to crash (and hopefully log the error, too). I need some guidance on how I should do this. My current approach doesn't seem like good design:
Abbreviated module code:
class Configuration:
def __init__( self ):
self.config_file='config.ini'
self.config = ConfigParser.ConfigParser()
def config_is_readable( self ):
if os.path.exists(self.config_file):
try:
self.config.read(self.config_file)
except ConfigParser.Error, err:
print "Cannot parse configuration file. %s" % err
return False
except IOError, err:
print "Problem opening configuration file. %s" % err
return False
else:
print 'Cannot open file.'
return False
#print 'Config file is readable!'
return True
def config_has_correct_syntax( self ):
# Check section syntax via regex
for section in self.config.sections():
if self.__pattern_section.match( section ) is None:
print 'Error: Syntax of section <%s> is wrong' % section
return False
Main code:
class Bot( BotInterface):
def __init__( self , module , bot , param , oplist , logger ):
# Instantiate a Configuration object and get configuration variables
self.race_config = Configuration( bot.arena.lower() )
if self.race_config.config_is_readable() and self.race_config.config_has_correct_syntax():
if bot.arena in self.race_config.get_section_list(2):
self.cmd_tracks = self.race_config.get_cmd_tracks()
self.coords = self.race_config.get_all_options()
self.default_track = self.race_config.get_default_track()
self.tracks = self.race_config.get_track_and_id( arena_only=False )
else:
logger.error('Sorry, bot can only handle the following arenas: ' + ', '.join(self.race_config.get_section_list(2)) )
bot.disconnectFromServer()
else:
logger.error('Could not open/parse configuration file.')
bot.disconnectFromServer()
What I'm doing now is checking from the main code if self.race_config.config_is_readable() and self.race_config.config_has_correct_syntax() and disconnect if either returns False. Ideally, I want to call both of these functions in the module's constructor method, but if I do that, how would I crash the main bot if one of the functions return False?
This is also my first time trying to catch exceptions... Is that how I should be catching ConfigParser errors?
Thanks for any help, and please let me know if there's anything I can clarify...