def write_config(self, first_time=False): global config_fields config = ConfigParser() for section in config_fields.keys(): config.add_section(section) for key in config_fields[section].keys(): if first_time: config.set(section, key, config_fields[section][key]) else: config.set(section, key, getattr(self, key)) with open(self.config_file, 'w') as cfg: config.write(cfg) return config
def __init__(self, pname, verbs): self.program_name = pname self.verbs = verbs global config_fields first_time = False if not os.path.exists(self.config_dir): os.makedirs(self.config_dir) if os.path.exists(self.config_file): config = self.read_config() else: first_time = True config = self.write_config(first_time) for section in config_fields.keys(): for key in config_fields[section].keys(): try: self.config_options.append(key) setattr(self, key, config.get(section, key)) except Exception: print "Please fix `%s` in %s" % (key, self.config_file) sys.exit() if first_time: print "Welcome! Using `set` configure the necessary settings:" print " ".join(sorted(self.config_options)) print "Config file:", self.config_file print "For debugging, tail -f", self.log_file, "\n" self.prompt = self.prompt.strip() + " " # Cosmetic fix for prompt logging.basicConfig(filename=self.log_file, level=logging.DEBUG, format=log_fmt) logger.debug("Loaded config fields:\n%s" % map(lambda x: "%s=%s" % (x, getattr(self, x)), self.config_options)) cmd.Cmd.__init__(self) if not os.path.exists(self.config_file): config = self.write_config() try: if os.path.exists(self.history_file): readline.read_history_file(self.history_file) atexit.register(readline.write_history_file, self.history_file) except IOError: print("Error: history support")