# Erebus IRC bot - Author: John Runyon
+# vim: fileencoding=utf-8
# "Config" class (reading/providing access to bot.config)
-import ConfigParser
+from __future__ import print_function
+import sys, os
+
+if sys.version_info.major < 3:
+ import ConfigParser
+else:
+ import configparser as ConfigParser
class Config(object):
def __init__(self, filename, writeout=True):
- self.__dict__['config'] = ConfigParser.SafeConfigParser()
+ self.__dict__['config'] = ConfigParser.RawConfigParser(delimiters=('=',))
self.__dict__['filename'] = filename
self.__dict__['writeout'] = writeout
self.config.read(filename)
def __setattr__(self, key, value):
self.config.set('erebus', key, value)
+ def __getitem__(self, section): #!! READ-ONLY !!
+ return {item: self.config.get(section, item) for item in self.config.options(section)}
+
def level(self, cmd):
return self.config.get('levels', cmd)
return self.config.get(section, key)
except:
return default
+ def getint(self, section, key, default=0):
+ try:
+ return int(self.config.get(section, key))
+ except:
+ return default
+ def getboolean(self, section, key, default=False):
+ val = self.get(section, key, default)
+ if type(val) is bool:
+ return val
+ elif val == "0" or val.lower() == "false":
+ return False
+ else:
+ return True
def set(self, section, key, value):
- self.config.set(section, key, value)
+ if not self.config.has_section(section):
+ self.config.add_section(section)
+ self.config.set(section, key, str(value))
+ if self.writeout: self.write()
+
+ def delete(self, section, key):
+ if self.config.has_section(section):
+ self.config.remove_option(section, key)
+ if self.writeout: self.write()
def write(self):
- with open(self.filename, 'wb') as configfile:
+ with open(self.filename+'.tmp', 'w') as configfile:
self.config.write(configfile)
+ os.rename(configfile.name, self.filename)
def __del__(self):
if self.writeout: self.write()
-
if __name__ == '__main__':
import sys
- cfg = Config(sys.argv[1], False)
+ if len(sys.argv) > 1:
+ cfg = Config(sys.argv[1], False)
+ else:
+ cfg = Config('bot.config', False)
for s in cfg.config.sections():
for k, v in cfg.items(s):
- print s+'.'+k, '=', v
-# for k, v in cfg.items():
-# print 'erebus.'+k, '=', v
+ print("[%r][%r] = %r" % (s, k, v))