def load_config(self): self.fileconfig = ConfigParser.RawConfigParser() res = self.fileconfig.read(self.conffile) if not res: raise ConfigParser.Error("Unable to open config file %s" % (self.conffile, )) if self.bglogger is not None: ConfigLogger(self.fileconfig, self.bglogger) self.mcu = mcu.MCU(self, ConfigWrapper(self, 'mcu')) if self.debugoutput is not None: self.mcu.connect_file(self.debugoutput, self.dictionary) if self.fileconfig.has_section('extruder'): self.objects['extruder'] = extruder.PrinterExtruder( self, ConfigWrapper(self, 'extruder')) if self.fileconfig.has_section('fan'): self.objects['fan'] = fan.PrinterFan(self, ConfigWrapper(self, 'fan')) if self.fileconfig.has_section('heater_bed'): self.objects['heater_bed'] = heater.PrinterHeater( self, ConfigWrapper(self, 'heater_bed')) self.objects['toolhead'] = toolhead.ToolHead( self, ConfigWrapper(self, 'printer')) # Validate that there are no undefined parameters in the config file valid_sections = dict([(s, 1) for s, o in self.all_config_options]) for section in self.fileconfig.sections(): section = section.lower() if section not in valid_sections: raise ConfigParser.Error("Unknown config file section '%s'" % (section, )) for option in self.fileconfig.options(section): option = option.lower() if (section, option) not in self.all_config_options: raise ConfigParser.Error( "Unknown option '%s' in section '%s'" % (option, section))
def get_opt_tags(self, section, option, tags): """ Supplement to ConfigParser.ConfigParser.get(). This will search for an option in [section] and if it doesn't find it will also try in [section-tag] for every value of tag in tags. Will raise a ConfigParser.Error if it cannot find a value. Parameters ----------- self : ConfigParser object The ConfigParser object (automatically passed when this is appended to the ConfigParser class) section : string The section of the ConfigParser object to read option : string The ConfigParser option to look for tags : list of strings The name of subsections to look in, if not found in [section] Returns -------- string The value of the options being searched for """ # Need lower case tag name; also exclude cases with tag=None if tags: tags = [tag.lower() for tag in tags if tag is not None] try: return self.get(section, option) except ConfigParser.Error: err_string = "No option '%s' in section [%s] " % (option, section) if not tags: raise ConfigParser.Error(err_string + ".") return_vals = [] sub_section_list = [] for sec_len in range(1, len(tags) + 1): for tag_permutation in itertools.permutations(tags, sec_len): joined_name = '-'.join(tag_permutation) sub_section_list.append(joined_name) section_list = ["%s-%s" % (section, sb) for sb in sub_section_list] err_section_list = [] for sub in sub_section_list: if self.has_section('%s-%s' % (section, sub)): if self.has_option('%s-%s' % (section, sub), option): err_section_list.append("%s-%s" % (section, sub)) return_vals.append( self.get('%s-%s' % (section, sub), option)) # We also want to recursively go into sections if not return_vals: err_string += "or in sections [%s]." \ %("] [".join(section_list)) raise ConfigParser.Error(err_string) if len(return_vals) > 1: err_string += "and multiple entries found in sections [%s]."\ %("] [".join(err_section_list)) raise ConfigParser.Error(err_string) return return_vals[0]
def load_config(self): self.fileconfig = ConfigParser.RawConfigParser() res = self.fileconfig.read(self.conffile) if not res: raise ConfigParser.Error("Unable to open config file %s" % ( self.conffile,)) if self.bglogger is not None: ConfigLogger(self.fileconfig, self.bglogger) self.mcu = mcu.MCU(self, ConfigWrapper(self, 'mcu')) if self.debugoutput is not None: self.mcu.connect_file(self.debugoutput, self.dictionary) # Create printer components config = ConfigWrapper(self, 'printer') for m in [extruder, fan, heater, toolhead]: m.add_printer_objects(self, config) # Validate that there are no undefined parameters in the config file valid_sections = { s: 1 for s, o in self.all_config_options } for section in self.fileconfig.sections(): section = section.lower() if section not in valid_sections: raise ConfigParser.Error("Unknown config file section '%s'" % ( section,)) for option in self.fileconfig.options(section): option = option.lower() if (section, option) not in self.all_config_options: raise ConfigParser.Error( "Unknown option '%s' in section '%s'" % ( option, section))
def _add_option(self, optname, value=None, line=None, sep='='): if value is None and line is None: raise ConfigParser.Error('Either value or line must be passed in') elif value and line: raise ConfigParser.Error('value and line are mutually exclusive') if value is not None: line = '%s%s%s' % (optname, sep, value) opt = self._find(optname) if opt: opt.format(line) else: self._lines.append(OptionLine(optname, line))
def read_oms_config_file(): # Reads the oms config file # Returns: AgentID config value if os.path.isfile(OMS_ADMIN_CONFIG_FILE): try: keyvals = config_file_to_kv_pair(OMS_ADMIN_CONFIG_FILE) return keyvals[AGENT_ID].strip() except ConfigParser.NoSectionError, exception: log(DEBUG, exception.message) raise ConfigParser.Error(exception.message) except ConfigParser.NoOptionError, exception: log('DEUBG', exception.message) raise ConfigParser.Error(exception.message)
def validate_config(self): valid_sections = dict([(s, 1) for s, o in self.all_config_options]) for section in self.fileconfig.sections(): section = section.lower() if section not in valid_sections: raise ConfigParser.Error("Unknown config file section '%s'" % (section, )) for option in self.fileconfig.options(section): option = option.lower() if (section, option) not in self.all_config_options: raise ConfigParser.Error( "Unknown option '%s' in section '%s'" % (option, section))
def get_opt_tags(self, section, option, tags): """ Supplement to ConfigParser.ConfigParser.get(). This will search for an option in [section] and if it doesn't find it will also try in [section-tag] for every value of tag in tags. Will raise a ConfigParser.Error if it cannot find a value. Parameters ----------- self : ConfigParser object The ConfigParser object (automatically passed when this is appended to the ConfigParser class) section : string The section of the ConfigParser object to read option : string The ConfigParser option to look for tags : list of strings The name of subsections to look in, if not found in [section] Returns -------- string The value of the options being searched for """ # Need lower case tag name; also exclude cases with tag=None if tags: tags = [tag.lower() for tag in tags if tag is not None] try: return self.get(section, option) except ConfigParser.Error: errString = "No option '%s' in section [%s] " %(option,section) if not tags: raise ConfigParser.Error(errString + ".") returnVals = [] sectionList = ["%s-%s" %(section, tag) for tag in tags] for tag in tags: if self.has_section('%s-%s' %(section, tag)): if self.has_option('%s-%s' %(section, tag), option): returnVals.append(self.get('%s-%s' %(section, tag), option)) if not returnVals: errString += "or in sections [%s]." %("] [".join(sectionList)) raise ConfigParser.Error(errString) if len(returnVals) > 1: errString += "and multiple entries found in sections [%s]."\ %("] [".join(sectionList)) raise ConfigParser.Error(errString) return returnVals[0]
def read_oms_primary_workspace_config_file(): # Reads the oms config file # Returns: AgentID config value if os.path.isfile(OMS_ADMIN_CONFIG_FILE): # the above path always points to the oms configuration file of the primary workspace try: keyvals = config_file_to_kv_pair(OMS_ADMIN_CONFIG_FILE) return keyvals[OMS_WORKSPACE_ID_KEY].strip( ), keyvals[AGENT_ID].strip() except ConfigParser.NoSectionError, exception: log(DEBUG, exception.message) raise ConfigParser.Error(exception.message) except ConfigParser.NoOptionError, exception: log(DEBUG, exception.message) raise ConfigParser.Error(exception.message)
def read_worker_state(): # Reads the state.config file and returns the values of pid, workspace_id, resource_running_version if os.path.isfile(WORKER_STATE_FILE_PATH): state = ConfigParser.ConfigParser() try: state.read(WORKER_STATE_FILE_PATH) pid = state.get(STATE_SECTION, PID) workspace_id = state.get(STATE_SECTION, WORKSPACE_ID) resource_running_version = state.get(STATE_SECTION, DSC_RESOURCE_VERSION) except ConfigParser.NoSectionError, exception: log(DEBUG, exception.message) raise ConfigParser.Error(exception.message) except ConfigParser.NoOptionError, exception: log(DEBUG, exception.message) raise ConfigParser.Error(exception.message)
def test_error(self): import pickle e1 = ConfigParser.Error('value') pickled = pickle.dumps(e1) e2 = pickle.loads(pickled) self.assertEqual(e1.message, e2.message) self.assertEqual(repr(e1), repr(e2))
def fromfile(self, file_like): """Load model from config file (both header and parameters). Parameters ---------- file-like : object File-like object with readline() method representing config file """ defaults = dict((p.name, p._to_str(p.default_value)) for p in self) if future.utils.PY2: cfg = configparser.SafeConfigParser(defaults) else: cfg = configparser.ConfigParser(defaults, inline_comment_prefixes=(';', '#')) try: cfg.readfp(file_like) if cfg.sections() != ['header', 'params']: raise configparser.Error( 'Expected sections not found in model file') except configparser.Error as exc: filename = getattr(file_like, 'name', '') msg = 'Could not construct %s from %s\n\nOriginal exception: %s' % \ (self.__class__.__name__, ('file %r' % (filename,)) if filename else 'file-like object', str(exc)) raise BadModelFile(msg) self.header = dict(cfg.items('header')) for param in defaults: self.header.pop(param.lower()) for param in self: param.value_str = cfg.get('params', param.name)
def get_controller_commands(self): """Returns a list of strings, each of which may be given to subprocess.Popen to start one controller. """ CTRL_TYPES = ('PRT', 'GTF', 'CUSTOM') ctrl_exes = self._get_controller_executables() items = self.config_parser.items('Controllers') cmd_dict = {} # keyed by num, value is executable string args_dict = {} # keyed by num, value is arguments string for (name, value) in items: try: prefix, num = name.split('_') num = int(num) if prefix == 'ctrl': if value.upper() in CTRL_TYPES: cmd_dict[num] = ctrl_exes[value.upper()] else: raise ConfigParser.Error( "Acceptable values for a 'ctrl_N' entry in the [Controllers] section of a configuration file are 'PRT', 'GTF', or 'CUSTOM' but the value '%s' was supplied." % value) elif prefix == 'args': args_dict[num] = value except ValueError: pass result = [] for key, value in cmd_dict.iteritems(): try: result.append(value + ' ' + args_dict[key]) except IndexError: result.append(value) return result
def __init__(self, *files): "Initialize the capability dictionary" ConfigParser.RawConfigParser.__init__(self) if not files: files = ["gpscap.ini", "/usr/share/gpsd/gpscap.ini"] self.read(files) # Resolve uses= members while True: keepgoing = False for section in self.sections(): if self.has_option(section, "uses"): parent = self.get(section, "uses") if self.has_option(parent, "uses"): continue # Found a parent section without a uses = part. for heritable in self.options(parent): if not self.has_option(section, heritable): self.set(section, heritable, self.get(parent, heritable)) keepgoing = True self.remove_option(section, "uses") if not keepgoing: break # Sanity check: All items must have a type field. for section in self.sections(): if not self.has_option(section, "type"): raise ConfigParser.Error("%s has no type" % section) elif self.get(section, "type") not in ("engine", "vendor", "device"): raise ConfigParser.Error("%s has invalid type" % section) # Sanity check: All devices must point at a vendor object. # Side effect: build the lists of vendors and devices. self.vendors = [] self.devices = [] for section in self.sections(): if self.get(section, "type") == "vendor": self.vendors.append(section) if self.get(section, "type") == "device": self.devices.append(section) self.vendors.sort() for section in self.sections(): if self.get(section, "type") == "device": if not self.has_option(section, "vendor"): raise ConfigParser.Error("%s has no vendor" % section) if self.get(section, "vendor") not in self.vendors: raise ConfigParser.Error("%s has invalid vendor" % section)
def test_error(self): import pickle e1 = ConfigParser.Error('value') 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(repr(e1), repr(e2))
def __init__(self, pin_params): if PWM is None: raise ConfigParser.Error("PWM is not supported!") channel = pin_params['chip'].get_pin_number(pin_params['pin']) GPIO.setup(channel, GPIO.OUT) self.pwm = GPIO.PWM(channel, 1) # 1Hz self.pwm.start(0) self.duty = .0 self.freq = 1
def read_omsconfig_file(): if os.path.isfile(OMS_ADMIN_CONFIG_FILE): # the above path always points to the oms configuration file of the primary workspace keyvals = config_file_to_kv_pair(OMS_ADMIN_CONFIG_FILE) return keyvals else: error_string = "could not find file " + OMS_ADMIN_CONFIG_FILE log(DEBUG, error_string) raise ConfigParser.Error(error_string)
def convert_ini(module, path): repo = RepoParser() try: with open(path) as fp: repo.readfp(fp) except IOError as e: raise ConfigParser.Error("Failed to read {}: {}".format(path, e)) return repo.as_dict()
def setUp(self): config = ConfigParser.SafeConfigParser() config.read(_TEST_CONFIG_PATHS) if not config.has_section('tratihubis'): raise ConfigParser.Error(u'test user and password must be specified in section [tratihubis] ' \ + 'in one of the following files: %s' % _TEST_CONFIG_PATHS) password = config.get('tratihubis', 'password') user = config.get('tratihubis', 'user') self.hub = github.Github(user, password)
def get_workspaceid_agentid_from_oms_config(): # Reads the oms config file # Returns: AgentID config value keyvals = read_omsconfig_file() try: return keyvals[OPTION_OMS_WORKSPACE_ID].strip(), keyvals[OPTION_AGENT_ID].strip() except KeyError, exception: log(DEBUG, str(exception)) raise ConfigParser.Error(str(exception))
def set_config_file(self, filename): filename = os.path.abspath(filename) self.config_path = filename self.config_dir = os.path.dirname(filename) + os.path.sep self.config_parser = ConfigParser.SafeConfigParser() # Parse the config file if not self.config_parser.read( self.config_path): # returned an empty list raise ConfigParser.Error("Unable to read config file: " + self.config_path)
def load_datasets_settings(configurationFile, global_config): defaultByKey = {'here': global_config['here']} configParser = ConfigParser.ConfigParser(defaultByKey) if not configParser.read(configurationFile): raise ConfigParser.Error('Could not open %s' % configurationFile) datasets_settings = {} for key, value in configParser.items('datasets:mistic'): datasets_settings[key] = value return datasets_settings
def run(self, terms, variables=None, **kwargs): ret = [] for term in terms: repo = RepoParser() path = os.path.expanduser(term) try: with open(path) as fp: repo.readfp(fp) except IOError as e: raise ConfigParser.Error("Failed to read {}: {}".format( term, e)) ret.append(repo.as_dict()) return ret
def getConfig(): #config config_file = "3par.conf" config = ConfigParser.SafeConfigParser() if not config.read(config_file): raise ConfigParser.Error("Unable to read config file") host = config.get('3par', 'host') login = config.get('3par', 'login') password = config.get('3par', 'password') default_cpg = config.get('3par', 'default_cpg') snap_cpg = config.get('3par', 'snap_cpg') return (host, login, password, default_cpg, snap_cpg)
def read_omsconfig_file(): if os.path.isfile(OMS_ADMIN_CONFIG_FILE): # the above path always points to the oms configuration file of the primary workspace keyvals = config_file_to_kv_pair(OMS_ADMIN_CONFIG_FILE) if os.path.isfile(OMS_AGENTID_FILE): # OMS_AGENTID_FILE is a new addition to the omsagent. If the file is not present, the agentid is supposed to be present in the OMS_ADMIN_CONFIG_FILE agentid_file = open(OMS_AGENTID_FILE, "r") agent_id = agentid_file.read().strip() agentid_file.close() keyvals[OPTION_AGENT_ID] = agent_id return keyvals else: error_string = "could not find file " + OMS_ADMIN_CONFIG_FILE log(DEBUG, error_string) raise ConfigParser.Error(error_string)
def load_settings(configurationPath, basePath): 'Load settings' defaultByKey = {'here': basePath} configParser = ConfigParser.ConfigParser(defaultByKey) if not configParser.read(configurationPath): raise ConfigParser.Error('Could not open %s' % configurationPath) settings = {} for key, value in configParser.items('app:tcd'): if 'use' == key: if value.startswith('config:'): settings.update( load_settings(value.replace('config:', ''), basePath)) settings[key] = value settings.update(load_sensitive_settings(configurationPath, defaultByKey)) return settings
def __init__(self, filename='/etc/ganeti/extstorage/eql.conf'): ''' Constructor ''' self.config = ConfigParser.SafeConfigParser() if not self.config.read(filename): raise ConfigParser.Error("Unable to read config file") self.device_hostname = self.config.get('default', 'device_hostname') self.management_ip = self.config.get('default', 'management_ip') self.management_user = self.config.get('default', 'management_user') self.management_password = self.config.get('default', 'management_password') self.storage_net = self.config.get('default', 'storage_net') self.storage_ip = self.config.get('default', 'storage_ip') self.storage_port = self.config.get('default', 'storage_port')
def __init__(cls, switch, vendor, cred_dir, vendordir, database_link=None, connect=True, debug_stdout=False, enable_pass=None, retry_times=5): cls.vendor = netvendor.CustomVendorStrings(vendor, vendordir) cls.switch = switch cls.enpass = enable_pass cls.debug = debug_stdout cls.cmderrors = [] if connect: cfg_file = os.path.join(cred_dir, vendor + ".credentials") if not os.path.exists(cfg_file): cfg_file = os.path.join(cred_dir, ".credentials") cls.ssh_credentials = ConfigParser.RawConfigParser() cls.ssh_credentials.read(cfg_file) # Enable password is optional parameter try: if not enable_pass: cls.enpass = cls.ssh_credentials.get( 'Credentials', 'enable') except ConfigParser.Error: pass # User / pass credentials are mandatory try: user = cls.ssh_credentials.get('Credentials', 'username') passwd = cls.ssh_credentials.get('Credentials', 'password') except ConfigParser.Error: raise ConfigParser.Error("No valid credentials file found at"+\ " %s" % cfg_file) for retry in range(1, retry_times + 1): try: cls.connect(user, passwd, debug_stdout) break except pexpect.ExceptionPexpect: if retry == retry_times: raise continue
def _set_solver_config(comp): """Setup solver configuration""" parser = ConfigParser.RawConfigParser() parser.optionxform = str # keep param names case parser.readfp(StringIO(comp.solver_parameters)) solver_config = cysolver.Configuration.get() errors = [] for section in parser.sections(): for optname, value in parser.items(section): try: value = _CONFIG_MAP[optname](value) except ValueError: errors.append('bad option value for %s: %r' % (optname, value)) continue except KeyError: continue setattr(solver_config, optname, value) if errors: raise ConfigParser.Error(os.linesep.join(errors))
def __init__(self, options, positional_args): """Takes the output of an OptionParser.parse_args() call as inputs.""" self.options = options if len(positional_args) > 1: raise ConfigParser.Error( "Expected no more than one positional command line argument, but was supplied with: %s" % positional_args) self.config_path = None self.config_parser = None self.config_dir = None # Config file if len(positional_args) == 1: self.set_config_file(positional_args[0]) self.initialize_logging() elif options.config_path != None: self.set_config_file(options.config_path) self.initialize_logging()
def load_config(self): self.fileconfig = ConfigParser.RawConfigParser() res = self.fileconfig.read(self.conffile) if not res: raise ConfigParser.Error("Unable to open config file %s" % (self.conffile, )) if self.debugoutput is None: ConfigLogger(self.fileconfig) self.mcu = mcu.MCU(self, ConfigWrapper(self, 'mcu')) if self.fileconfig.has_section('fan'): self.objects['fan'] = fan.PrinterFan(self, ConfigWrapper(self, 'fan')) if self.fileconfig.has_section('extruder'): self.objects['extruder'] = extruder.PrinterExtruder( self, ConfigWrapper(self, 'extruder')) if self.fileconfig.has_section('heater_bed'): self.objects['heater_bed'] = heater.PrinterHeater( self, ConfigWrapper(self, 'heater_bed')) self.objects['toolhead'] = toolhead.ToolHead( self, ConfigWrapper(self, 'printer'))