def validate_config_file(config): if not config.has_section('mysqld'): raise ConfigParser.NoSectionError('Section mysqld was not found!') if not config.has_option('mysqld', 'host'): raise_option_not_found('mysqld', 'host') if not config.has_option('mysqld', 'user'): raise_option_not_found('mysqld', 'user') if not config.has_option('mysqld', 'password'): raise_option_not_found('mysqld', 'password') if not config.has_section('robinhood'): raise ConfigParser.NoSectionError('Section robinhood was not found!') if not config.has_option('robinhood', 'database'): raise_option_not_found('robinhood', 'database') if not config.has_option('robinhood', 'acct_stat_table'): raise_option_not_found('robinhood', 'acct_stat_table') if not config.has_section('history'): raise ConfigParser.NoSectionError('Section history was not found!') if not config.has_option('history', 'database'): raise_option_not_found('history', 'database') if not config.has_option('history', 'acct_stat_history_table'): raise_option_not_found('history', 'acct_stat_history_table') if not config.has_option('chart', 'num_top_groups'): raise_option_not_found('chart', 'num_top_groups') if not config.has_option('chart', 'save_dir'): raise_option_not_found('chart', 'save_dir') if not config.has_option('chart_pie', 'filename'): raise_option_not_found('chart_pie', 'filename') if not config.has_option('chart_pie', 'filetype'): raise_option_not_found('chart_pie', 'filetype') if not config.has_section('mail'): raise ConfigParser.NoSectionError('Section mail was not found!') if not config.has_option('mail', 'server'): raise_option_not_found('mail', 'server') if not config.has_option('mail', 'sender'): raise_option_not_found('mail', 'sender') if not config.has_option('mail', 'recipient_list'): raise_option_not_found('mail', 'recipient_list') if not config.has_option('storage', 'filesystem'): raise_option_not_found('storage', 'filesystem')
def getConfig(self): section = 'RADIOD' if not self.configOK: return # Get options config.read(ConfigFile) try: options = config.options(section) for option in options: parameter = config.get(section, option) msg = "Config option: " + option + " = " + parameter log.message(msg, log.DEBUG) if option == 'loglevel': next elif option == 'mpdport': self.mpdport = parameter elif option == 'dateformat': self.dateFormat = parameter else: msg = "Invalid option " + option + ' in section ' \ + section + ' in ' + ConfigFile log.message(msg, log.ERROR) except ConfigParser.NoSectionError: msg = ConfigParser.NoSectionError(section), 'in', ConfigFile log.message(msg, log.ERROR) return
def loadConfig(ini_path,defsection=None): """ loads a config without sections (if defsection=None) or `defsection` section otherwise. returns a params dictionary with key-values mirroring the ones in config/section. """ section='__root__' if defsection is None else defsection ini_str = '[%s]\n'%section + open(ini_path, 'r').read() ini_fp = StringIO.StringIO(ini_str) config = ConfigParser.ConfigParser() config.optionxform=str config.readfp(ini_fp) rParams=dict(config.items(section)) if len(rParams)==0: raise ConfigParser.NoSectionError("section %s does not exist or is empty"%section) item=None;value=None for k in rParams.keys(): item=k; value=rParams[k] try: rParams[k]=eval(rParams[k]) except Exception as inst: extra=" config item:%s value:%s "%(k,value) inst.args =inst.args+(extra,) inst.message += extra raise return rParams
def getConfig(self): section = 'RADIOD' option = 'loglevel' strLogLevel = 'INFO' # Get loglevel option config.read(ConfigFile) try: strLogLevel = config.get(section, option) except ConfigParser.NoSectionError: msg = ConfigParser.NoSectionError(section), 'in', ConfigFile self.message(msg, self.ERROR) if strLogLevel == "CRITICAL": loglevel = self.CRITICAL elif strLogLevel == "ERROR": loglevel = self.ERROR elif strLogLevel == "WARNING": loglevel = self.WARNING elif strLogLevel == "INFO": loglevel = self.INFO elif strLogLevel == "DEBUG": loglevel = self.DEBUG elif strLogLevel == "NONE": loglevel = self.NONE else: loglevel = self.INFO return loglevel
def items(self, section, raw=False, vars=None, defaults=True): if defaults: return IncludingConfigParser.items(self, section, raw=raw, vars=vars) else: d = collections.OrderedDict() try: d.update(self._sections[section]) except KeyError: if section != ConfigParser.DEFAULTSECT: raise ConfigParser.NoSectionError(section) # Update with the entry specific variables if vars: for key, value in vars.items(): d[self.optionxform(key)] = value options = d.keys() if "__name__" in options: options.remove("__name__") if raw: return [(option, d[option]) for option in options] else: return [(option, self._interpolate(section, option, d[option], d)) for option in options]
def initialise(config_file): """Initialise configuration module""" global cfg, required_options try: cfg = ConfigParser.ConfigParser() cfg.readfp(open(config_file)) #Check for required section if (not cfg.has_section('dbAlerter')): raise ConfigParser.NoSectionError('dbAlerter') #Initialise configuration defaults for option, value in default_options.items(): if (not cfg.has_option('dbAlerter', option)): cfg.set('dbAlerter', option, value) #Check for required options for option in required_options: if (not cfg.has_option('dbAlerter', option)): raise ConfigParser.NoOptionError(option, 'dbAlerter') except IOError: notify.notify("Error", 'Failed to open config file: ' + config_file, 'Failed to open config file: ' + config_file) sys.exit(1) except ConfigParser.NoSectionError: sys.exit(1) except ConfigParser.NoOptionError: sys.exit(1)
def load_rc_object(rc_file, section, object): """ Read keys and values corresponding to one settings location to the qutiprc file. Parameters ---------- rc_file : str String specifying file location. section : str Tags for the saved data. object : Object Object to overwrite. All attribute's type must be one of bool, int, float, complex, str. """ config = configparser.ConfigParser() config.read(full_path(rc_file)) if not config.has_section(section): raise configparser.NoSectionError(section) keys = object.__all opts = config.options(section) for op in opts: if op in keys: reader = get_reader(getattr(object, op), config) setattr(object, op, reader(section, op)) else: warnings.warn("Invalid qutip config variable in qutiprc: " + op)
def check_config(interpret): sections = globals() for section in options.sections: if not section in sections: raise ConfigParser.NoSectionError(section) for opt_section, option in options.booleans: if opt_section == section and option not in sections[section]: raise ConfigParser.NoOptionError(option, section) for opt_section, option in options.floats: if opt_section == section and option not in sections[section]: raise ConfigParser.NoOptionError(option, section) for opt_section, option in options.integers: if opt_section == section and option not in sections[section]: raise ConfigParser.NoOptionError(option, section) for opt_section, option in options.lists: if opt_section == section and option not in sections[section]: raise ConfigParser.NoOptionError(option, section) for opt_section, option in options.strings: if opt_section == section and option not in sections[section]: raise ConfigParser.NoOptionError(option, section) if interpret: __interpret_config()
def section(self, section): if section not in self._configSections: if self.has_section(section): self._configSections[section] = ConfigSection(self, section) else: raise ConfigParser.NoSectionError(section) return self._configSections[section]
def getConfig(self): section = 'DAEMON' if not self.configOK: return # Get options config.read(ConfigFile) try: options = config.options(section) for option in options: parameter = config.get(section, option) msg = "Config option: " + option + " = " + parameter log.message(msg, log.DEBUG) if option == 'displaywidth': log.message("Setting Display Width to " + parameter, log.INFO) self.display_width = int(parameter) else: msg = "Invalid option " + option + ' in section ' \ + section + ' in ' + ConfigFile log.message(msg, log.ERROR) except ConfigParser.NoSectionError: msg = ConfigParser.NoSectionError(section), 'in', ConfigFile log.message(msg, log.ERROR) return
def get_protocol(cp, log): """Get the protocol from a ConfigParser object, defaulting to STOMP.""" try: if 'sender' in cp.sections(): protocol = cp.get('sender', 'protocol') elif 'receiver' in cp.sections(): protocol = cp.get('receiver', 'protocol') else: raise ConfigParser.NoSectionError('sender or receiver') if protocol not in (Ssm2.STOMP_MESSAGING, Ssm2.AMS_MESSAGING): raise ValueError except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): # If the newer configuration setting 'protocol' is not set, use 'STOMP' # for backwards compatability. protocol = Ssm2.STOMP_MESSAGING log.warn("No option set for 'protocol'. Defaulting to %s.", protocol) except ValueError: log.critical("Invalid protocol '%s' set. Must be either '%s' or '%s'.", protocol, Ssm2.STOMP_MESSAGING, Ssm2.AMS_MESSAGING) log.critical('SSM will exit.') print('SSM failed to start. See log file for details.') sys.exit(1) return protocol
def __getattr__(self, item): try: return object.__getattribute__(self, item) except AttributeError: if self.has_section(item): return Section(self, item) raise ConfigParser.NoSectionError(item)
def set(self, section, option, value): if not self.static_conf.has_section(section): raise configparser.NoSectionError(section) if not self.static_conf.has_option(section, option): raise configparser.NoOptionError(option, section) if not self.dynamic_conf.has_section(section): self.dynamic_conf.add_section(section) self.dynamic_conf.set(section, option, value)
def option_source(self, section, option): option = self.optionxform(option) try: return self._origin[(section, option)] except KeyError: if not self.has_section(section): raise ConfigParser.NoSectionError(section) raise ConfigParser.NoOptionError(option, section)
def test_nosectionerror(self): import pickle e1 = ConfigParser.NoSectionError('section') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled) self.assertEqual(e1.message, e2.message) self.assertEqual(e1.args, e2.args) self.assertEqual(e1.section, e2.section) self.assertEqual(repr(e1), repr(e2))
def get_value(self, section, option): for cfg in self.configs: try: return cfg.get_value(section, option) except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): pass if not self.has_section(section): raise ConfigParser.NoSectionError(section) raise ConfigParser.NoOptionError(option, section)
def test_nosectionerror(self): import pickle e1 = ConfigParser.NoSectionError('section') for proto in range(pickle.HIGHEST_PROTOCOL + 1): pickled = pickle.dumps(e1, proto) e2 = pickle.loads(pickled) self.assertEqual(e1.message, e2.message) self.assertEqual(e1.args, e2.args) self.assertEqual(e1.section, e2.section) self.assertEqual(repr(e1), repr(e2))
def options(self, section): """Return a list of option names for the given section name.""" section = self.sectionxform(section) try: opts = self.__sections[section].copy() except KeyError: raise ConfigParser.NoSectionError(section) if opts.has_key('__name__'): del opts['__name__'] return opts.keys()
def validate_config_file(config): if not config.has_section('mysqld'): raise ConfigParser.NoSectionError('Section mysqld was not found!') if not config.has_option('mysqld', 'host'): raise_option_not_found('mysqld', 'host') if not config.has_option('mysqld', 'user'): raise_option_not_found('mysqld', 'user') if not config.has_option('mysqld', 'password'): raise_option_not_found('mysqld', 'password') if not config.has_section('history'): raise ConfigParser.NoSectionError('Section history was not found!') if not config.has_option('history', 'database'): raise_option_not_found('history', 'database') if not config.has_option('history', 'acct_stat_history_table'): raise_option_not_found('history', 'acct_stat_history_table') if not config.has_section('robinhood'): raise ConfigParser.NoSectionError('Section robinhood was not found!') if not config.has_option('robinhood', 'database'): raise_option_not_found('robinhood', 'database') if not config.has_option('robinhood', 'acct_stat_table'): raise_option_not_found('robinhood', 'acct_stat_table') if not config.has_section('mail'): raise ConfigParser.NoSectionError('Section mail was not found!') if not config.has_option('mail', 'server'): raise_option_not_found('mail', 'server') if not config.has_option('mail', 'sender'): raise_option_not_found('mail', 'sender') if not config.has_option('mail', 'recipient'): raise_option_not_found('mail', 'recipient')
def has_rc_key(rc_file, key): config = configparser.ConfigParser() config.read(rc_file) if config.has_section('qutip'): opts = config.options('qutip') if key in opts: return True else: return False else: raise configparser.NoSectionError('qutip')
def get(self, section, option): try: _section = self._sections[section] except KeyError: raise ConfigParser.NoSectionError(section) try: _option = _section[option] except KeyError: raise ConfigParser.NoOptionError(option, section) return _option
def remove_option(self, section, option): """Remove an option.""" section = self.sectionxform(section) try: sectdict = self.__sections[section] except KeyError: raise ConfigParser.NoSectionError(section) option = self.optionxform(option) existed = sectdict.has_key(option) if existed: del sectdict[option] return existed
def valueItems(self): """Usefull when you don't care about the name of the items.""" if not self.__dict__["__configuration"]. \ has_section(self.__dict__["__section_name"]) and \ self.__dict__["__section_name"]!="DEFAULT": raise ConfigParser.NoSectionError(self.__dict__["__section_name"]) tmpList = self.__dict__["__configuration"]. \ items(self.__dict__["__section_name"]) retVal = [] for element in tmpList: retVal.append(element[1]) return retVal
def get_all_configs(cls, section): '''Get All configurations''' try: confs = cls.configParrser.items(section) except ConfigParser.NoSectionError: if len(cls.loaded_config_file) == 0: raise ConfigParser.NoSectionError( 'No configuration file find.') else: msg = 'Load config file failed: No section [{}]\nConfig file: {}'.format( section, cls.loaded_config_file) raise ConfigParser.NoSectionError(msg) except ConfigParser.InterpolationSyntaxError as e: raise ConfigParser.InterpolationSyntaxError( "Config file syntax error: {}".format(e)) except Exception as e: raise Exception(e) # https://stackoverflow.com/questions/5466618/too-many-values-to-unpack-iterating-over-a-dict-key-string-value-list # 环境变量(大写)优先于配置文件 return {key: os_getenv(key.upper(), val) for key, val in confs}
def open(self): conf_path = os.path.expanduser('~/.dualscope123') conf = ConfigParser.ConfigParser() if not os.path.isfile(conf_path): raise Exception("Please configure %s section " % (conf_path) + " eth_nios with hostname and port") conf.read([conf_path]) if not 'eth_nios' in conf.sections(): raise ConfigParser.NoSectionError( "Please configure ~/.dualscope123 section" + "eth_nios with hostname and port") self.HOSTNAME = conf.get('eth_nios', 'hostname').strip("\"'") self.PORT = conf.get('eth_nios', 'port').strip("\"'")
def add_comment(self, section, comment): """ Add a comment :param section: The section where to place the comment :param comment: The comment to add """ if not section or section == "DEFAULT": sectdict = self._defaults else: try: sectdict = self._sections[section] except KeyError: raise ConfigParser.NoSectionError(section) sectdict['; %s' % (comment, )] = None
def __getattr__(self, key): if not self.__dict__["__configuration"]. \ has_section(self.__dict__["__section_name"]) and \ self.__dict__["__section_name"]!="DEFAULT": raise ConfigParser.NoSectionError(self.__dict__["__section_name"]) if not self.__dict__["__configuration"]. \ has_option(self.__dict__["__section_name"], key): raise ConfigParser. \ NoOptionError(key, self.__dict__["__section_name"]) return self.__dict__["__configuration"]. \ get(self.__dict__["__section_name"], key)
def remove_option(self, section, option): """Remove an option.""" if section == ConfigParser.DEFAULTSECT: sectdict = self._defaults else: try: sectdict = self._sections[section] except KeyError: raise ConfigParser.NoSectionError(section) option = self.optionxform(option) existed = option in sectdict if existed: del sectdict[option] return existed
def get(self, key): section, option = key.split('.') if section not in self._parser.sections(): raise ConfigParser.NoSectionError(section) opts = self._parser.options(section) for _opt in opts: if '!' not in _opt: typ = 'str' else: opt, typ = _opt.split('!', 1) if opt == option: return self._parser._get(section, CONV_FUNC[typ], _opt) else: raise ConfigParser.NoOptionError(option)
def test_conf_get_section_exec(open_mock, write_mock, set_mock, add_mock, read_mock, set_config_mock, set_vars_mock): set_vars_mock.return_value = None set_config_mock.return_value = None e = configparser.NoSectionError("Test Error") read_mock.side_effect = e result = Config().conf_get('test_section', 'test_option', 'test_value') assert read_mock.call_count == 1 assert add_mock.call_count == 1 assert set_mock.call_count == 1 assert open_mock.call_count == 1 assert write_mock.call_count == 1 assert result == 'test_value'