def getViewsForModule(self, module, model): """ @param module: the name of the model to get the views for @param model: the L{commitmessage.model.Model} to initialize views with @return: the configured views for a module """ viewLine = ConfigParser.get(self, module, 'views') p = re.compile(',\s?') viewNames = [name.strip() for name in p.split(viewLine) if len(name.strip()) > 0] userMap = self.userMap views = [] for viewName in viewNames: fullClassName = ConfigParser.get(self, 'views', viewName) view = getNewInstance(fullClassName) view.__init__(viewName, model) # Setup default values if ConfigParser.has_section(self, viewName): for name in ConfigParser.options(self, viewName): value = ConfigParser.get(self, viewName, name, 1) view.__dict__[name] = str(Itpl(value)) # Setup module-specific values forViewPrefix = re.compile('^%s.' % viewName) for option in ConfigParser.options(self, module): if forViewPrefix.search(option): # Take off the 'viewName.' name = option[len(viewName)+1:] value = ConfigParser.get(self, module, option, 1) view.__dict__[name] = str(Itpl(value)) views.append(view) return views
def readROIFile(hfile): cp = ConfigParser() cp.read(hfile) roiout = [] try: rois = cp.options('rois') except: print 'rois not found' return [] for a in cp.options('rois'): if a.lower().startswith('roi'): iroi = int(a[3:]) name, dat = cp.get('rois',a).split('|') xdat = [int(i) for i in dat.split()] dat = [(xdat[0], xdat[1]), (xdat[2], xdat[3]), (xdat[4], xdat[5]), (xdat[6], xdat[7])] roiout.append((iroi, name.strip(), dat)) roiout = sorted(roiout) calib = {} calib['CAL_OFFSET'] = cp.get('calibration', 'OFFSET') calib['CAL_SLOPE'] = cp.get('calibration', 'SLOPE') calib['CAL_QUAD'] = cp.get('calibration', 'QUAD') calib['CAL_TWOTHETA'] = ' 0 0 0 0' return roiout, calib
def from_file(cls, file_name): """ Make a Config from a file. """ file_name = os.path.expanduser(file_name) parser = ConfigParser() # IMPORTANT: Turn off downcasing of option names. parser.optionxform = str parser.read(file_name) cfg = Config() if parser.has_section('index_values'): for repo_id in parser.options('index_values'): cfg.version_table[repo_id] = ( parser.getint('index_values', repo_id)) if parser.has_section('request_usks'): for repo_dir in parser.options('request_usks'): cfg.request_usks[repo_dir] = parser.get('request_usks', repo_dir) if parser.has_section('insert_usks'): for repo_id in parser.options('insert_usks'): cfg.insert_usks[repo_id] = parser.get('insert_usks', repo_id) # ignored = fms_id|usk_hash|usk_hash|... if parser.has_section('fmsread_trust_map'): cfg.fmsread_trust_map.clear() # Wipe defaults. for ordinal in parser.options('fmsread_trust_map'): fields = parser.get('fmsread_trust_map', ordinal).strip().split('|') Config.validate_trust_map_entry(cfg, fields) cfg.fmsread_trust_map[fields[0]] = tuple(fields[1:]) Config.update_defaults(parser, cfg) cfg.file_name = file_name return cfg
class PrintersConfig: def __init__(self): self.Config = ConfigParser() self.Config2 = ConfigParser() self.Config.read(os.path.join("/etc/printerstats/config", "printers.ini")) self.Config2.read(os.path.join("/etc/printerstats/config", "config.ini")) def ConfigMap(self, section): dict1 = {} options = self.Config2.options(section) for option in options: dict1[option] = self.Config2.get(section, option) return dict1 def CampusMap(self, section): dict1 = {} options = self.Config.options(section) for option in options: dict1[section] = self.Config.get(section, option) return dict1 def ConfigMapPrinters(self, section): dict1 = {section: {}} options = self.Config.options(section) for option in options: dict1[section][option] = self.Config.get(section, option) return dict1
def main(): cp = ConfigParser() cp.read(sys.argv[1]) certfile = cp.get('sslexport', 'pemfile') external = cp.get('sslexport', 'external') internal = '127.0.0.1' # External (SSL) listeners for ext_port in cp.options('sslexport.server'): ipport = cp.get('sslexport.server', ext_port) ip,port = ipport.split(':') server = gevent.server.StreamServer( (external, int(ext_port)), Forwarder(ip, port, gevent.socket.socket), certfile=certfile) server.start() print 'ssl(%s:%s) => clear(%s:%s)' % ( external, ext_port, ip, port) # Internal (non-SSL) listeners for int_port in cp.options('sslexport.client'): ipport = cp.get('sslexport.client', int_port) ip,port = ipport.split(':') server = gevent.server.StreamServer( (internal, int(int_port)), Forwarder(ip, port, lambda:gevent.ssl.SSLSocket(gevent.socket.socket())), certfile=certfile) server.start() print 'clear(%s:%s) => ssl(%s:%s)' % ( internal, int_port, ip, port) while True: gevent.sleep(10) print '--- mark ---'
def readROIFile(hfile): cp = ConfigParser() cp.read(hfile) output = [] for a in cp.options('rois'): if a.lower().startswith('roi'): iroi = int(a[3:]) name, dat = cp.get('rois',a).split('|') xdat = [int(i) for i in dat.split()] dat = [(xdat[0], xdat[1]), (xdat[2], xdat[3]), (xdat[4], xdat[5]), (xdat[6], xdat[7])] output.append((iroi, name.strip(), dat)) roidata = sorted(output) calib = {} caldat = cp.options('calibration') for attr in ('offset', 'slope', 'quad'): calib[attr] = [float(x) for x in cp.get('calibration', attr).split()] dxp = {} ndet = len(calib['offset']) for attr in cp.options('dxp'): tmpdat = [x for x in cp.get('dxp', attr).split()] if len(tmpdat) == 2*ndet: tmpdat = ['%s %s' % (i, j) for i, j in zip(tmpdat[::2], tmpdat[1::2])] try: dxp[attr] = [int(x) for x in tmpdat] except ValueError: try: dxp[attr] = [float(x) for x in tmpdat] except ValueError: dxp[attr] = tmpdat return roidata, calib, dxp
def createDictFromConfig(): """ Read the configuration from scipion/config/scipionbox.conf. A dictionary will be created where each key will be a section starting by MICROSCOPE:, all variables that are in the GLOBAL section will be inherited by default. """ # Read from users' config file. confGlobalDict = OrderedDict() confDict = OrderedDict() cp = ConfigParser() cp.optionxform = str # keep case (stackoverflow.com/questions/1611799) confFile = pw.getConfigPath("scipionbox.conf") print "Reading conf file: ", confFile cp.read(confFile) GLOBAL = "GLOBAL" MICROSCOPE = "MICROSCOPE:" if not GLOBAL in cp.sections(): raise Exception("Missing section %s in %s" % (GLOBAL, confFile)) else: for opt in cp.options(GLOBAL): confGlobalDict[opt] = cp.get(GLOBAL, opt) for section in cp.sections(): if section != GLOBAL and section.startswith(MICROSCOPE): sectionDict = OrderedDict(confGlobalDict) for opt in cp.options(section): sectionDict[opt] = cp.get(section, opt) confDict[section.replace(MICROSCOPE, '')] = sectionDict return confDict
def read_properties(self, property_file="Coordinator.properties"): """ process properties file """ ## Reads the configuration properties cfg = ConfigParser() cfg.read(property_file) self.install_dir = cfg.get("config", "install_dir") self.euca_rc_dir = cfg.get("config", "euca_rc_dir") self.initial_cluster_size = cfg.get("config", "initial_cluster_size") self.max_cluster_size = cfg.get("config", "max_cluster_size") self.bucket_name = cfg.get("config", "bucket_name") self.instance_type = cfg.get("config", "instance_type") self.cluster_name = cfg.get("config", "cluster_name") self.hostname_template = cfg.get("config", "hostname_template") self.reconfigure = cfg.get("config", "reconfigure") self.cluster_type = cfg.get("config", "cluster_type") self.db_file = cfg.get("config", "db_file") self.add_nodes = cfg.get("config", "add_nodes") self.rem_nodes = cfg.get("config", "rem_nodes") self.cloud_api_type = cfg.get("config", "cloud_api_type") self.trans_cost = cfg.get("config", "trans_cost") self.gain = cfg.get("config", "gain") self.serv_throughput = cfg.get("config", "serv_throughput") try: self.gamma = cfg.get("config", "gamma") except: self.gamma = 0 ## Reads the monitoring thresholds self.thresholds_add = {} self.thresholds_remove = {} for option in cfg.options("thresholds_add"): self.thresholds_add[option] = cfg.get("thresholds_add", option) for option in cfg.options("thresholds_remove"): self.thresholds_remove[option] = cfg.get("thresholds_remove", option)
def readScanConfig(sfile): cp = ConfigParser() cp.read(sfile) scan = {} for a in cp.options('scan'): scan[a] = cp.get('scan',a) general = {} for a in cp.options('general'): general[a] = cp.get('general',a) return scan, general
def readROIFile(hfile,xrd=False): cp = ConfigParser() cp.read(hfile) output = [] if xrd: for a in cp.options('xrd1d'): if a.lower().startswith('roi'): iroi = int(a[3:]) name,unit,dat = cp.get('xrd1d',a).split('|') lims = [float(i) for i in dat.split()] dat = [lims[0], lims[1]] output.append((iroi, name.strip(), unit.strip(), dat)) return sorted(output) else: for a in cp.options('rois'): if a.lower().startswith('roi'): iroi = int(a[3:]) name, dat = cp.get('rois',a).split('|') lims = [int(i) for i in dat.split()] ndet = int(len(lims)/2) dat = [] for i in range(ndet): dat.append((lims[i*2], lims[i*2+1])) output.append((iroi, name.strip(), dat)) roidata = sorted(output) calib = {} caldat = cp.options('calibration') for attr in ('offset', 'slope', 'quad'): calib[attr] = [float(x) for x in cp.get('calibration', attr).split()] extra = {} ndet = len(calib['offset']) file_sections = cp.sections() for section in ('dxp', 'extra'): if section not in file_sections: continue for attr in cp.options(section): tmpdat = [x for x in cp.get(section, attr).split()] if len(tmpdat) == 2*ndet: tmpdat = ['%s %s' % (i, j) for i, j in zip(tmpdat[::2], tmpdat[1::2])] try: extra[attr] = [int(x) for x in tmpdat] except ValueError: try: extra[attr] = [float(x) for x in tmpdat] except ValueError: extra[attr] = tmpdat return roidata, calib, extra
def __init__(self, cfg_file): PARSER = ConfigParser() PARSER.read(cfg_file) for cfg_section in PARSER.sections(): # First round, create objects for cfg_option in PARSER.options(cfg_section): setattr(self, cfg_section, self.StandInObject()) # Second round, add attributes for cfg_option in PARSER.options(cfg_section): # Set the values for the section options setattr(getattr(self, cfg_section), cfg_option, PARSER.get(cfg_section, cfg_option))
def read_stageconfig(filename=None, _larch=None): """read Sample Stage configurattion file, saving results Parameters ---------- filename: None or string, name of file holding sample positions (see Note) Examples -------- read_stageconfig() Notes ------ 1. If filename is None (the default) 'SampleStage_autosave.ini' from the current working folder is used. 2. the file timestamp is always tested to find new position names 3. Generally, you don't need to do this explicitly, as move_samplestage will run this when necessary. """ if filename is None: filename = DEF_SampleStageFile if not os.path.exists(filename): print 'No stageconfig found!' return None #endif stages = [] positions = OrderedDict() ini = ConfigParser() ini.read(filename) for item in ini.options('stages'): line = ini.get('stages', item) words = [i.strip() for i in line.split('||')] stages.append(words[0]) #endfor for item in ini.options('positions'): line = ini.get('positions', item) words = [i.strip() for i in line.split('||')] name = words[0].lower() vals = [float(i) for i in words[2].split(',')] positions[name] = vals #endfor this = Group(pos=positions, stages=stages, _modtime_=os.stat(filename).st_mtime) if _larch is not None: if not _larch.symtable.has_group('macros'): _larch.symtable.new_group('macros') _larch.symtable.macros.stage_conf = this print(" Read %d positions from stage configuration." % len(positions) ) return this
class TesseraConfig(object): def __init__(self, path): self._path = path self._config = ConfigParser() if os.path.exists(path): self._parse() def get_path(self): return self._path def _parse(self): self._config.read(self._path) def has_option(self, section, option): try: self._config.get(section, option) return True except: return False def get_option_index(self, section, option): try: options = self._config.options(section) except: return -1 try: return options.index(option) except: return -1 def get_option_name(self, section, idx): try: options = self._config.options(section) except: return "?" if idx == None: return "no " + section return options[idx] def get(self, section, option): try: return self._config.get(section, option) except NoSectionError: raise ConfigSectionNotFoundError(section, self._path) except NoOptionError: raise ConfigOptionNotFoundError(option, section, self._path) def set(self, section, option, value): self._config.set(section, option, value) def store(self): with open(self._path, "w") as f: self._config.write(f)
def generate_config(): config_parser = ConfigParser() current_directory = os.path.dirname(os.path.abspath(__file__)) config_parser.read(os.path.normpath(os.path.join(current_directory, '..', 'secrets', 'secrets.ini'))) config = dict(zip([option.upper() for option in config_parser.options('core')], [config_parser.get('core', y) for y in config_parser.options('core')])) for section in [s for s in config_parser.sections() if s != 'core']: config[section] = ConfigStruct(dict(zip(config_parser.options(section), [config_parser.get(section, y) for y in config_parser.options(section)]))) return config
def writeConfigFiles2Database(self): print '-------------------------------------------------------------------------- start write config2SQL' cParser = ConfigParser() cParser.read(self.CUON_FS + '/user.cfg') try: sP = cParser.get('password',self.POSTGRES_USER) print sP sID = self.xmlrpc_createSessionID(self.POSTGRES_USER, sP) dicUser = {'Name': self.POSTGRES_USER, 'SessionID':sID, 'userType':'cuon' } print '2-------------------------------------------------------------------------- start write config2SQL ', dicUser #clients sSql = "select id from clients where status != 'delete'" result = self.xmlrpc_executeNormalQuery(sSql, dicUser ) print '3-------------------------------------------------------------------------- start write config2SQL ', sSql, result if result and result not in self.liSQL_ERRORS: for row in result: client_id = row["id"] cpSection = "CLIENT_" + `client_id` cParser = ConfigParser() cParser.read(self.CUON_FS + '/clients.ini') print '4-------------------------------------------------------------------------- start write config2SQL' if cParser. has_section(cpSection): print cParser.options(cpSection) for sOptions in self.liClientsOptions: print '5-------------------------------------------------------------------------- start write config2SQL ', cpSection, sOptions sValue = self.getConfigOption(cpSection, sOptions, cParser) if sValue: print '6-------------------------------------------------------------------------- start write config2SQL ', cpSection, sOptions, sValue sSql = "select * from fct_write_config_value(" + `client_id` + ", '" + 'clients.ini' + "', '" + cpSection + "', '" + sOptions + "', '" + sValue + "' ) " print sSql self.xmlrpc_executeNormalQuery(sSql, dicUser) sSql = "select * from fct_get_config_option(1,'clients.ini', 'client_1', 'order_main_headline_articles_id') " print sSql result = self.xmlrpc_executeNormalQuery(sSql, dicUser) print result except Exception, params: print Exception, params
def init_from_options(self): # If a config file is provided, read it into the ABACManager if self._options.config: cp = ConfigParser() cp.optionxform=str cp.read(self._options.config) for name in cp.options('Principals'): cert_file = cp.get('Principals', name) self.register_id(name, cert_file) for name in cp.options('Keys'): key_file = cp.get('Keys', name) self.register_key(name, key_file) if 'Assertions' in cp.sections(): for assertion in cp.options('Assertions'): self.register_assertion(assertion) if 'AssertionFiles' in cp.sections(): for assertion_file in cp.options("AssertionFiles"): self.register_assertion_file(assertion_file) # Use all the other command-line options to override/augment # the values in the ABCManager # Add new principal ID's / keys if self._options.id: for id_filename in options.id: parts = id_filename.split(':') id_name = parts[0].strip() id_cert_file = None if len(parts) > 1: id_cert_file = parts[1].strip() self.register_id(id_name, id_cert_file) id_key_file = None if len(parts) > 2: id_key_file = parts[2].strip() self.register_key(name, id_key_file) # Register assertion files provided by command line if self._options.assertion_file: for assertion_file in self._options.assertion_file: self.register_assertion_file(assertion_file) # Grab pure ABAC assertions from commandline if self._options.assertion: for assertion in self._options.assertion: self.register_assertion(assertion)
def parse_ini(path, names): """ Parse the deployment file. This function parses the deployment file, searching for sections that specify rulesets; these sections should have the name ``wsgirewrite:``, followed by the name of the ruleset. Eg:: [wsgirewrite:blocked] cond1 = %{REMOTE_HOST} !^.*example.com$ rule1 = ^.*$ - F The ruleset aboved is called "blocked", and will be applied if it is in the parameter ``names``. Condition and rules are sorted by their names, which should start with ``cond`` and ``rule``, respectively. """ from ConfigParser import ConfigParser # Read the deployment file. config = ConfigParser() config.read(path) names = names.split() # Get relevant sections. sections = [section for section in config.sections() if section.startswith('wsgirewrite:') and section.split(':')[1] in names] rulesets = [] for section in sections: conditions = [] directives = [] # Parse config. conds = [option for option in config.options(section) if option.startswith('cond')] conds.sort() rules = [option for option in config.options(section) if option.startswith('rule')] rules.sort() for cond in conds: line = config.get(section, cond) conditions.append(parse_line(line)) for rule in rules: line = config.get(section, rule) directives.append(parse_line(line)) rulesets.append((conditions, directives)) return rulesets
def registerStats(config_file): print "===============================" print "Parsing stats config.ini file..." print config_file print "===============================" config = ConfigParser() if not config.read(config_file): print "ERROR: config file '", config_file, "' not found!" sys.exit(1) print "\nRegistering Stats..." stats = Stats() per_cpu_stat_groups = config.options('PER_CPU_STATS') for group in per_cpu_stat_groups: i = 0 per_cpu_stats_list = config.get('PER_CPU_STATS', group).split('\n') for item in per_cpu_stats_list: if item: stats.register(item, group, i, True) i += 1 per_l2_stat_groups = config.options('PER_L2_STATS') for group in per_l2_stat_groups: i = 0 per_l2_stats_list = config.get('PER_L2_STATS', group).split('\n') for item in per_l2_stats_list: if item: for l2 in range(num_l2): if num_l2 > 1: name = re.sub("#", str(l2), item) else: name = re.sub("#", "", item) stats.register(name, group, i, False) i += 1 other_stat_groups = config.options('OTHER_STATS') for group in other_stat_groups: i = 0 other_stats_list = config.get('OTHER_STATS', group).split('\n') for item in other_stats_list: if item: stats.register(item, group, i, False) i += 1 stats.createStatsRegex() return stats
def values(self): # get schemas defaults schema = self._schema_ values = self._default_values_() # let's parse configuration file cp = ConfigParser() cp.read(self._configuration_file_) # Sections verifications unused_sections = [section for section in cp.sections() \ if section not in schema.keys()] if unused_sections != []: raise ConfigurationSectionNotUsed, \ "Section(s) not used in configuration file : %s" % \ ' '.join(unused_sections) not_found_sections = [section for section in schema.keys() \ if section not in cp.sections()] if not_found_sections != []: raise ConfigurationSectionNotFound, \ "Section(s) not found in configuration file : %s" % \ ' '.join(not_found_sections) # Options verifications and merging for section in schema: not_used_options = [option for option in cp.options(section) \ if option not in schema[section] and not '_any_' in schema[section]] if not_used_options != []: raise ConfigurationOptionNotUsed, \ 'Option(s) not used in section \'%s\' : %s' % \ (section, ' '.join(not_used_options)) for option in cp.options(section): if option in schema[section]: t = schema[section][option]['type'] elif 'any' in schema[section]: t = schema[section]['_any_']['type'] try: v = t( cp.get(section,option) ) except ValueError: raise ConfigurationOptionTypeMismatch, \ 'Option \'%s\' must be \'%s\'' % (option, t.__name__) if section == 'default': values[option] = v else: values['%s.%s' % (section, option)] = v return values
def getDataSources(fName = None): ''' return data sources directories for this machine. directories are defined in datasources.ini or provided filepath''' import socket from ConfigParser import ConfigParser pcName = socket.gethostname() p = ConfigParser() p.optionxform = str if fName is None: fName = 'datasources.ini' p.read(fName) if pcName not in p.sections(): raise NameError('Host name section %s not found in file %s' %(pcName,fName)) dataSources = {} for option in p.options(pcName): dataSources[option] = p.get(pcName,option) return dataSources
def read(): """ Loads default variables from the 'resources/settings.ini' file. Arguments: - None. Return: - None. """ try: p = BuiltIn().get_variable_value('${resources_path}') if p is not None: _settingsFullFileName = join(p, _settingsFileName) else: _settingsFullFileName = join(getcwd(), 'resources', _settingsFileName) conf = ConfigParser() conf.read(_settingsFullFileName) for setting in conf.options('default'): BuiltIn().set_global_variable('${%s}' % setting, conf.get('default', setting)) except: pass
def restore_rois(self, roifile): """restore ROI setting from ROI.dat file""" cp = ConfigParser() cp.read(roifile) rois = [] self.mcas[0].clear_rois() prefix = self.mcas[0]._prefix if prefix.endswith('.'): prefix = prefix[:-1] iroi = 0 for a in cp.options('rois'): if a.lower().startswith('roi'): name, dat = cp.get('rois', a).split('|') lims = [int(i) for i in dat.split()] lo, hi = lims[0], lims[1] roi = ROI(prefix=prefix, roi=iroi) roi.left = lo roi.right = hi roi.name = name.strip() rois.append(roi) iroi += 1 epics.poll(0.050, 1.0) self.mcas[0].set_rois(rois) cal0 = self.mcas[0].get_calib() for mca in self.mcas[1:]: mca.set_rois(rois, calib=cal0)
def get_params(args, params_file): """Extracts 'alignments' and 'annotations' parameters from either args or params_file""" def override(section, names): for name in names: value = getattr(args, name) if not params.has_key(section): params[section] = {} if not params[section].has_key(name) or value is not None: params[section][name] = value params = {} if params_file is not None and os.path.exists(params_file): cfg = ConfigParser() cfg.read(params_file) for section in cfg.sections(): params[section] = {} for option in cfg.options(section): value = cfg.get(section, option) if value.lower() in ('true', 'false'): if value.lower() == 'true': value = True else: value = False elif ' ' in value: value = value.split() elif value.isspace(): value = None params[section][option] = value override('alignments', ('genome_index', 'transcripts_fasta', 'sort_mem')) override('annotations', ('genome_fasta', 'gtf', 'suppl_annot')) return params
def _load_configuration(environment, path): """Loads a given configuration file specified by path and environment header (ini file). returns a key value representing the configuration. Values enclosed in {} are automatically decrypted using the $FURTHER_PASSWORD variable. Values that equal [RND] will be replaced with a random string.""" # Read configuration file parser = ConfigParser() parser.read(path) config = {} for option in parser.options(environment): value = parser.get(environment, option) # Handle encrypted configuration if (re.match(r'^\{.*\}$', value)): encrypted_value = re.match(r'^\{(.*)\}$', value).group(1) value = (local('decrypt.sh input="' + encrypted_value + '" password=$FURTHER_PASSWORD algorithm="PBEWithSHA1AndDESede" verbose="false"', capture=True)) # Handle random values if (re.match(r'\[RND\]', value)): value = _random_string() config[option] = value; return config
def _set_config_all(self, path_to_file): out = sys.stdout if not os.access(path_to_file, os.R_OK): self.log.warning( "cannot access file %s" % path_to_file ) return elif not self.env.config: self.log.warning( "cannot access config file trac.ini" ) return cfg = ConfigParser() cfg.read(path_to_file) if os.access(self.env.path, os.W_OK): path_to_trac_ini = os.path.join(self.env.path, 'conf', 'trac.ini') shutil.copy(path_to_trac_ini, path_to_trac_ini + '.bak') out.write( "created a backup of trac.ini to %s.bak" % path_to_trac_ini ) out.write('\n') else: out.write( "could not create backup of trac.ini - continue anyway? [y|n] " ) input = sys.stdin.readline() if not input or not input.strip() == 'y': return for sect in cfg.sections(): for opt in cfg.options(sect): self.config.set(sect, opt, cfg.get(sect, opt)) out.write( "added config [%s] %s = %s" % (sect, opt, cfg.get(sect, opt)) ) out.write('\n') self.config.save()
def read_config(self, config_path): config_parser = ConfigParser() config_parser.read(config_path) for section in config_parser.sections(): for option in config_parser.options(section): value = config_parser.get(section, option) setattr(self, option, value)
def process_l10n_ini(inifile): """Read a Mozilla l10n.ini file and process it to find the localisation files needed by a project""" l10n = ConfigParser() l10n.readfp(open(path_neutral(inifile))) l10n_ini_path = os.path.dirname(inifile) for dir in l10n.get('compare', 'dirs').split(): frompath = os.path.join(l10n_ini_path, l10n.get('general', 'depth'), dir, 'locales', 'en-US') if verbose: print '%s -> %s' % (frompath, os.path.join(l10ncheckout, 'en-US', dir)) try: shutil.copytree(frompath, os.path.join(l10ncheckout, 'en-US', dir)) except OSError: print 'ERROR: %s does not exist' % frompath try: for include in l10n.options('includes'): include_ini = os.path.join( l10n_ini_path, l10n.get('general', 'depth'), l10n.get('includes', include) ) if os.path.isfile(include_ini): process_l10n_ini(include_ini) except TypeError: pass except NoSectionError: pass
def write_ini_config_file(self, command, data, client): """\ Write the new command configuration in the plugin configuration file """ try: # read the config file config = ConfigParser() config.read(command.plugin.config.fileName) # if there is no commands section if not config.has_section('commands'): raise NoSectionError('could not find <commands> section in ' 'plugin <%s> config file' % data['plugin_name']) # remove the old entry found = False for temp in config.options('commands'): search = temp.split('-')[0] if search == command.command: config.remove_option('commands', temp) found = True # set the new command option value config.set('commands', data['command_name'], data['command_level']) self.debug('%s command <%s> in plugin <%s> config file' % ('updated' if found else 'created new entry for', command.command, data['plugin_name'])) # write the updated configuration file with open(command.plugin.config.fileName, 'wb') as configfile: config.write(configfile) except (IOError, NoSectionError), e: self.warning('could not change plugin <%s> config file: %s' % (data['plugin_name'], e)) client.message('^7could not change plugin ^1%s ^7config file' % data['plugin_name'])
def _scan_plugins(): """Scan the plugins directory for .ini files and parse them to gather plugin meta-data. """ pd = os.path.dirname(__file__) ini = glob(os.path.join(pd, '*.ini')) for f in ini: cp = ConfigParser() cp.read(f) name = cp.sections()[0] meta_data = {} for opt in cp.options(name): meta_data[opt] = cp.get(name, opt) plugin_meta_data[name] = meta_data provides = [s.strip() for s in cp.get(name, 'provides').split(',')] valid_provides = [p for p in provides if p in plugin_store] for p in provides: if not p in plugin_store: print "Plugin `%s` wants to provide non-existent `%s`." \ " Ignoring." % (name, p) plugin_provides[name] = valid_provides plugin_module_name[name] = os.path.basename(f)[:-4]
def __init__(self, config_filename): locale.setlocale(locale.LC_ALL, '') assert os.path.isfile(config_filename), "Config file not found" local_config_parser = ConfigParser() local_config_parser.read(config_filename) product_info_filename = local_config_parser.get("Config", "info_produtos") self._printer_name = local_config_parser.get("Config", "impressora") assert os.path.isfile(product_info_filename), "Product info file not found" # Set barcode filename self._barcode_filename = os.path.join( os.path.dirname(product_info_filename), "barcode" ) cfg_parser = ConfigParser() cfg_parser.read(product_info_filename) self._primary_categories = dict(cfg_parser.items(self.PRIMARY_CATEGORY_SEC)) self._secondary_categories = dict(cfg_parser.items(self.SECONDARY_CATEGORY_SEC)) if cfg_parser.has_section(self.PRICE_SEC): self.price_list = [] for opt in sorted(cfg_parser.options(self.PRICE_SEC)): self.price_list.append(cfg_parser.getfloat(self.PRICE_SEC, opt)) else: self.price_list = [1.7, 2.21] self._label_header = cfg_parser.get("Label", "header").replace("\\n","\n") self._label_template = cfg_parser.get("Label", "label") self._labels_per_file = 30 self._product_unity = "pç" self._category_on_label = cfg_parser.getint("Geral", "cat_etiqueta")
def parse_config_files(self, filenames=None): from ConfigParser import ConfigParser if filenames is None: filenames = self.find_config_files() if DEBUG: print "Distribution.parse_config_files():" parser = ConfigParser() for filename in filenames: if DEBUG: print " reading", filename parser.read(filename) for section in parser.sections(): options = parser.options(section) opt_dict = self.get_option_dict(section) for opt in options: if opt != '__name__': val = parser.get(section, opt) opt = string.replace(opt, '-', '_') opt_dict[opt] = (filename, val) # Make the ConfigParser forget everything (so we retain # the original filenames that options come from) parser.__init__() # If there was a "global" section in the config file, use it # to set Distribution options. if self.command_options.has_key('global'): for (opt, (src, val)) in self.command_options['global'].items(): alias = self.negative_opt.get(opt) try: if alias: setattr(self, alias, not strtobool(val)) elif opt in ('verbose', 'dry_run'): # ugh! setattr(self, opt, strtobool(val)) else: setattr(self, opt, val) except ValueError, msg: raise DistutilsOptionError, msg
def ini_config(self, conf_fn): conf_section = 'main' if '#' in conf_fn: conf_fn, conf_section = conf_fn.split('#', 1) try: from ConfigParser import ConfigParser except ImportError: from configparser import ConfigParser p = ConfigParser() # Case-sensitive: p.optionxform = str if not os.path.exists(conf_fn): # Stupid RawConfigParser doesn't give an error for # non-existant files: raise OSError("Config file %s does not exist" % self.options.config_file) p.read([conf_fn]) p._defaults.setdefault('here', os.path.dirname(os.path.abspath(conf_fn))) possible_sections = [] for section in p.sections(): name = section.strip().lower() if (conf_section == name or (conf_section == name.split(':')[-1] and name.split(':')[0] in ('app', 'application'))): possible_sections.append(section) if not possible_sections: raise OSError( "Config file %s does not have a section [%s] or [*:%s]" % (conf_fn, conf_section, conf_section)) if len(possible_sections) > 1: raise OSError( "Config file %s has multiple sections matching %s: %s" % (conf_fn, conf_section, ', '.join(possible_sections))) config = {} for op in p.options(possible_sections[0]): config[op] = p.get(possible_sections[0], op) return config
class Config_opt(object): def __init__(self, file): self.file = file self.con_option = ConfigParser() self.con_option.read(self.file) def get_sections(self): return self.con_option.sections() def get_options(self, section): return self.con_option.options(section) def get_items(self, section): return dict(self.con_option.items(section)) def get_str(self, section, option): return self.con_option.get(section, option) def get_int(self, section, option): return self.con_option.get(section, option)
def run(self): global gl_conf_host while True: try: cf = ConfigParser() cf.read(DEF_CONF_FILE) if cf.has_section('host'): gl_conf_host = {} for opt in cf.options('host'): optv = cf.get('host', opt).strip() opt = opt.replace('.', r'\.') m = re.search('[?*]', opt) if m: opt = opt.replace('*', r'\w+').replace('?', r'.') gl_conf_host[opt] = optv #print gl_conf_host time.sleep(3) except: pass
def parse_user_config(filename, dependencies): ''' Read user_config and update the relevant fields ''' cparse = ConfigParser() cparse.read(filename) for dep_name in cparse.sections(): if not dep_name in dependencies.keys(): print('!! user_config specifies unknown dependency "{0}"'.format( dep_name)) Exit(0) # loop over options for that dependencies for opt in cparse.options(dep_name): if opt in VALID_FIELDS: dependencies[dep_name].__setattr__(opt, cparse.get(dep_name, opt)) else: print "Unknown build option: {0} for dependency {1}".format( opt, dep_name)
def read_config(cfg): """ read config fron ini :param cfg: :return: """ check_paths(cfg) r = {} config = ConfigParser() config.read(cfg) for section in config.sections(): r[section] = {} for option in config.options(section): value = config.get(section, option).strip().decode("utf-8") r[section][option] = value return r
def _load_config(self): path = 'config/pluggit.ini' filename = os.path.join(os.path.dirname(__name__), path) try: parser = ConfigParser() parser.read(filename) options = parser.options('pluggit') validate.pluggit_config(options) print options # DEBUG statement not strictly necessary, but would be nice... if 'debug' in options and parser.get('pluggit', 'debug') == '1': self.debug = True self.logger.info('loaded Pluggit configuration') except ConfigError as e: self.logger.error('no Pluggit config file found') exit(-1)
def readconf(rc,dic=None): config = ConfigParser() config.optionxform=str try: config.read( rc ) except BaseException as e: raise ValueError("Config Parser returns an error\'{}\'".format(e)) if dic is None: dic={} elif not type(dic) is dict: raise TypeError("Incorrect dictionary type") for section in config.sections(): if not section in dic: dic[section]={} elif not type(dic[section]) is dict: raise TypeError("Section {} in dictionary is not a dictionary") for option in config.options(section): dic[section][option] = config.get(section,option) return dic
def envs_conf(env_): defaults = { 'dbname': 'mootiro_maps', 'virtualenv': 'mootiro_maps', 'server_port': '8001', 'apache_conf': 'maps', 'maintenance_apache_conf': 'maps_maintenance' } required = ['hosts', 'dir', 'django_settings'] # Lets parse the config file to get the env attributes. conf = ConfigParser(defaults) conf.read(os.path.join(env.fabfile_dir, 'envs.conf')) available_envs = conf.sections() # Defining some messages to be displayed to user. usage_msg = 'Usage: fab use:<env> <command>' available_msg = ( 'The available envs are: "{envs}". ' 'To modify your environments edit the configuration file "envs.conf".' ).format(envs=', '.join(available_envs)) # The user should specify an env to use. if not env_: abort(''.join([ 'You should specify which "env" you want to use.\n', available_msg, '\n\n', usage_msg ])) # The env should be specified in the config file. if env_ not in available_envs: abort(''.join(['Environment not found: "{}".\n', available_msg]).format(env_)) # Verify if all required options were defined. not_defined = [i for i in required if i not in conf.options(env_)] if not_defined: abort('There are some required options not defined for "{}": {}.\n' 'Please, edit "envs.conf" file and fill all required options.\n'. format(env_, ', '.join(not_defined))) return conf
def createConf(fpath, ftemplate, remove=[], keep=[], notify=False): "Create config file in fpath following the template in ftemplate" # Remove from the template the sections in "remove", and if "keep" # is used only keep those sections. # Create directory and backup if necessary. dname = os.path.dirname(fpath) if not exists(dname): os.makedirs(dname) elif exists(fpath): if not exists(join(dname, 'backups')): os.makedirs(join(dname, 'backups')) backup = join(dname, 'backups', '%s.%d' % (basename(fpath), int(time.time()))) print(yellow("* Creating backup: %s" % backup)) os.rename(fpath, backup) # Read the template configuration file. print(yellow("* Creating configuration file: %s" % fpath)) print("Please edit it to reflect the configuration of your system.\n") cf = ConfigParser() cf.optionxform = str # keep case (stackoverflow.com/questions/1611799) assert cf.read(ftemplate) != [], 'Missing file: %s' % ftemplate for section in set(remove) - set(keep): cf.remove_section(section) if keep: for section in set(cf.sections()) - set(keep): cf.remove_section(section) # Update with our guesses. if 'BUILD' in cf.sections(): for options in [guessJava(), guessMPI()]: for key in options: if key in cf.options('BUILD'): cf.set('BUILD', key, options[key]) # Collecting Protocol Usage Statistics elif 'VARIABLES' in cf.sections(): checkNotify(cf, notify) # Create the actual configuration file. cf.write(open(fpath, 'w'))
def process_l10n_ini(inifile): """Read a Mozilla l10n.ini file and process it to find the localisation files needed by a project """ l10n = ConfigParser() with open(path_neutral(inifile), 'r') as fh: l10n.readfp(fh) l10n_ini_path = os.path.dirname(inifile) for dir in l10n.get('compare', 'dirs').split(): frompath = os.path.join(l10n_ini_path, l10n.get('general', 'depth'), dir, 'locales', 'en-US') topath = os.path.join(l10ncheckout, 'en-US', dir) if not os.path.exists(frompath): if verbose: print("[Missing source]: %s" % frompath) continue if os.path.exists(topath): if verbose: print("[Existing target]: %s" % topath) continue if verbose: print('%s -> %s' % (frompath, topath)) try: shutil.copytree(frompath, topath) except OSError as e: print(e) try: for include in l10n.options('includes'): include_ini = os.path.join( l10n_ini_path, l10n.get('general', 'depth'), l10n.get('includes', include) ) if os.path.isfile(include_ini): process_l10n_ini(include_ini) except TypeError: pass except NoSectionError: pass
def parse_config(): """Function to parse the config file.""" config_file = glob.glob('config.ini') if config_file: print 'Found a config file in working directory' else: cwd = os.path.abspath(os.path.dirname(__file__)) config_file = os.path.join(cwd, 'default_config.ini') print 'No config found. Using default.' config_dict = dict() parser = ConfigParser(allow_no_value=True) parser.read(config_file) for section in parser.sections(): for option in parser.options(section): config_dict[option] = parser.get(section, option) # Handle the proxy list info plist = config_dict.get('proxy_list') config_dict['proxy_list'] = plist.split(',') if type(plist) is str else [] return config_dict
def __init__(self, env): """Fills self with ticket-custom options with '(pref)' stripped from values. Maintains which options/rules have been configured for user preference.""" self.env = env self._pref_defaults = {} parser = ConfigParser() parser.optionxform = str # case sensitive options parser.read(self.env.config.filename) for key in parser.options('ticket-custom'): val = to_unicode(parser.get('ticket-custom', key)) for pref, default in PREF_DEFAULTS.items(): if val.endswith(pref): val = val.replace(pref, '').rstrip() self._pref_defaults[key] = default break self[key] = val # add built-in field types for field in TicketSystem(self.env).get_ticket_fields(): self[field['name']] = field['type']
def __stat_item_ls(self,flag): cp = ConfigParser( ); self.sec = 'statistics_items'; if flag == 'load': cp.read( self.__item_list_name ); self.sec = cp.sections()[0]; for opt in cp.options( self.sec ): val = cp.get( self.sec, opt ); idx = self.stat_item_list.InsertStringItem( 0, opt.decode('utf8') ); self.stat_item_list.SetStringItem( idx, 1, val ); # elif flag == 'save': cp.add_section( self.sec ); for i in range(self.stat_item_list.GetItemCount()): opt = self.stat_item_list.GetItem( i, col=0 ).Text.encode('utf8'); if opt == '': continue; val = self.stat_item_list.GetItem( i, col=1 ).Text.encode('utf8'); cp.set( self.sec, opt, val ); # cp.write( open(self.__item_list_name, 'w' ) );
def _prod_sg_rules(self): """ Return sg rules for all production networks """ vpc_config_file = "disco_vpc.ini" vpc_config = ConfigParser() vpc_config.read(vpc_config_file) prod_section = "envtype:production" self.assertTrue(vpc_config.has_section(prod_section)) # Since we only have one prod we shouldn't need duplicate config # but if this changes in the future we'll need to adjust the check # to inspect env and envtypes. self.assertFalse(vpc_config.has_section("env:prod")) sg_rule_names = [ name for name in vpc_config.options(prod_section) if name.endswith("sg_rules") ] return [vpc_config.get(prod_section, name) for name in sg_rule_names]
def _make_app(cls): base = os.path.dirname( os.path.dirname( os.path.dirname(os.path.dirname(os.path.realpath(__file__))))) # Parse in the options config = ConfigParser() config.read(os.path.join(base, "data/paste.ini")) ticketing_config = {} for section in config.sections(): section_config = {} ticketing_config[section] = section_config for option in config.options(section): try: section_config[option] = config.get(section, option) except InterpolationMissingOptionError: pass # Setup some properties ticketing_config["app:main"]["zodbconn.uri"] = "memory://testdb" ticketing_config["app:main"]["raven.testing"] = "true" # Setup the app return ticketing.main(ticketing_config, **ticketing_config["app:main"])
def loadConfig(section='tinymce'): """ Loads the default configuration from *config.ini*. The configuration is loaded from the *config.ini* file. `section` Section to load from config.ini. You can use config.ini to create multiple templates for the editor and name them differently. Returns a dictionary with tinymce configuration options """ boolean_settings = [ 'button_tile_map', 'apply_source_formatting', 'remove_linebreaks', 'relative_urls', 'convert_urls', 'paste_use_dialog', 'verify_html', 'theme_advanced_resizing' ] ret = {} config = ConfigParser() config.read(join(dirname(__file__), 'config.ini')) if config.has_section(section): for option in config.options(section): if option.strip() in boolean_settings: ret[option.strip()] = config.getboolean(section, option) else: ret[option.strip()] = config.get(section, option).strip() return ret
def set_stock_id_item(self, item_list_name, stock_id_file): cp = ConfigParser() cp.read(item_list_name) sec = cp.sections()[0] self.item_list = [] for opt in cp.options(sec): val = cp.get(sec, opt) if (val != '') & (opt != ''): val, num = re.subn(self.__stock_id_pat, 'STOCK_ID', val) self.__sheet_map[opt] = val self.item_list.append(opt) # fin = open(stock_id_file) self.stock_id_arr = fin.readlines() for stock_id in self.stock_id_arr: try: temp_id = int(stock_id) except: self.stock_id_arr.remove(stock_id) # self.tot_fetch_num = len(self.stock_id_arr) * len(self.__sheet_map)
def _hackPrimaryKeyFieldCP(cpdoc, idp, csvfile=os.path.join(os.path.dirname(__file__), '../conf/ldspk.csv')): '''temporary hack method to rewrite the layerconf primary key field for ConfigParser file types using Koordinates supplied PK CSV''' import io from ConfigParser import ConfigParser, NoSectionError cp = ConfigParser() #read CP from GC doc cp.readfp(io.BytesIO(LDSUtilities.recode(cpdoc, uflag='encode'))) #str(cpdoc #read the PK list writing any PK's found into CP for item in ConfigInitialiser.readCSV(csvfile): try: ky = item[2].replace('ogc_fid', '').replace('"', '').lstrip() for lt in LDSUtilities.LORT: ly = str(idp + lt + '-' + item[0]) #cant have a pk named ogc_fid since this is created automatically by the database, creating a new one crashes if cp.has_section(ly): cp.set(ly, 'pkey', ky) ldslog.debug('Setting PK on layer. ' + ly + '//' + ky) break else: raise NoSectionError('No section matching ' + idp + '|'.join(LDSUtilities.LORT) + '-' + item[0]) except NoSectionError as nse: ldslog.warn('PK hack CP: ' + str(nse) + ly + '//' + ky) #CP doesn't have a simple non-file write method?!? cps = "# LDS Layer Properties Initialiser - File\n" for section in cp.sections(): #ldslog.critical('writing >>>'+str(section)) cps += "\n[" + str(section) + "]\n" for option in cp.options(section): cps += str(option) + ": " + str(cp.get(section, option)) + "\n" return cps
def parse(cls, s): data = {} cfg = ConfigParser() s = "[ScribusScript]\n" + s cfg.readfp(StringIO(s)) options = cfg.options("ScribusScript") if not len(options): raise EmptyDescriptor for item in cls.items: if not item.name in options: if item.required: raise ValidationError, "Option %r required but not set" % item.name else: continue options.remove(item.name) value = cfg.get("ScribusScript", item.name) data[item.name] = item(value) if options: raise ValidationError, "Invalid options found: %s" % ", ".join( options) return cls(**data)
def main(): global gl_remote_server, gl_conf_host cf = ConfigParser() cf.read(DEF_CONF_FILE) if cf.has_section('dns'): gl_remote_server = {} for opt in cf.options('dns'): optv = cf.get('dns', opt).strip() cfg = optv.split('/') if len(cfg) > 1: gl_remote_server[cfg[0]] = cfg[1] else: DEF_REMOTE_SERVER = optv #另起一个线程 t = get_host() t.start() LocalDNSServer((DEF_LOCAL_HOST, DEF_PORT), LocalDNSHandler).serve_forever()
def compute(self): file_ = self.getInputFromPort("file") config = ConfigParser() config.optionxform = str # keep capital letter in model names config.read(file_.name) # read basic information variable_name = config.get('basic', 'variable_name') ref_filename = File() ref_filename.name = config.get('basic', 'ref_filename') self.setResult('variable_name', variable_name) self.setResult('ref_filename', ref_filename) # read model names file_names = [] model_names = config.options('file_names') for model in model_names: file_names.append(config.get('file_names', model)) self.setResult('file_names', file_names) self.setResult('model_names', model_names)
def upgrade_to_0_1_2(env, db, installed_version): if installed_version >= [0, 1, 2]: return trac_cfg = env.config['trac'] mainnav = trac_cfg.getlist('mainnav', []) try: i = mainnav.index('whiteboard') except ValueError: try: i = mainnav.index('roadmap') mainnav.insert(i + 1, 'whiteboard') trac_cfg.set('mainnav', ','.join(mainnav)) env.config.save() except: pass available_sections = [s for s in env.config.sections()] cfg = ConfigParser() cfg.read(resource_filename(__name__, 'sample.ini')) for section in cfg.sections(): if section[:6] != 'itteco' or section not in available_sections: target_cfg = env.config[section] for option in cfg.options(section): target_cfg.set(option, cfg.get(section, option)) custom = env.config['ticket-custom'] if 'business_value' not in custom or custom.get( 'business_value') != 'select': custom.set('business_value', 'select') custom.set('business_value.label', 'Business Value') custom.set('business_value.options', '|100|200|300|500|800|1200|2000|3000') if 'complexity' not in custom or custom.get('complexity') != 'select': custom.set('complexity', 'select') custom.set('complexity.label', 'Complexity') custom.set('complexity.options', '|0|1|2|3|5|8|13|21|34|55|89|134') env.config.save() env.log.debug("Upgrading: upgrade_to_0_1_2")
def _load_plugin_config(self, plugin, config_name): path = 'config/' + config_name.lower() + '.ini' filename = os.path.join(os.path.dirname(__name__), path) try: parser = ConfigParser() parser.read(filename) options = parser.options('app') validate.plugin_config(options) # DEBUG statement not strictly necessary, but would be nice... debug = False if 'debug' in options and parser.get('app', 'debug') == '1': debug = True plugin.configure(filename, debug, parser.get('app', 'user_agent'), parser.get('app', 'submission_subreddits'), parser.get('app', 'comment_subreddits')) except ConfigError as e: e._Error__message = 'no appropriate config file found' raise
def __addProtocolsFromConf(cls, protocols, protocolsConfPath): """ Load the protocols in the tree from a given protocols.conf file, either the global one in Scipion or defined in a plugin. """ # Populate the protocols menu from the plugin config file. if os.path.exists(protocolsConfPath): cp = ConfigParser() cp.optionxform = str # keep case cp.read(protocolsConfPath) # Ensure that the protocols section exists if cp.has_section('PROTOCOLS'): for menuName in cp.options('PROTOCOLS'): if menuName not in protocols: # The view has not been inserted menu = ProtocolConfig(menuName) children = json.loads(cp.get('PROTOCOLS', menuName)) for child in children: cls.__addToTree(menu, child, cls.__checkItem) protocols[menuName] = menu else: # The view has been inserted menu = protocols.get(menuName) children = json.loads(cp.get('PROTOCOLS', menuName)) cls.__findTreeLocation(menu.childs, children, menu)
def get_settings(section, config_file): """Read a given section from a config file and return it. :param str section: The section to read :param str config_file: The file to read from :return: A dictionary of settings :rtype: dict """ config = ConfigParser() config.read(config_file) dict1 = {} options = config.options(section) for option in options: try: dict1[option] = config.get(section, option) if dict1[option] == -1: print("skip: %s" % option) except: print("exception on %s!" % option) dict1[option] = None return dict1
def init_from_config(self, config): if isinstance(config, basestring): fname = config config = ConfigParser() config.read(fname) # read all WIKI properties and represent it as class properties for o in config.options(self.name): setattr(self, o, config.get(self.name, o).strip()) self.db_parameters.clear() if self.db[0] == '{': self.db_parameters = eval(self.db) else: for p in config.items(self.db): self.db_parameters[p[0]] = p[1] self.db = self._init_db() self.languages = [ language.strip() for language in config.get(self.name, "languages").split(',') ]
def exceptions_response(request): """ Handler for exception-mode. """ if not request.is_ajax(): return HttpResponseRedirect( reverse(index) + '?' + request.GET.urlencode()) account = get_account(request) if not account: return HttpResponseRedirect('/') config = ConfigParser() config.read(os.path.join(nav.path.sysconfdir, 'logger.conf')) options = config.options("priorityexceptions") excepts = [] context = {} for option in options: newpriority = config.get("priorityexceptions", option) excepts.append((option, newpriority)) context['exceptions'] = excepts context['exceptions_mode'] = True return render_to_response('syslogger/frag-exceptions.html', context, RequestContext(request))
def loadProtocolsConf(protocolsConf): """ Read the protocol configuration from a .conf file similar to the one in ~/.config/scipion/protocols.conf, which is the default one when no file is passed. """ # Helper function to recursively add items to a menu. def add(menu, item): "Add item (a dictionary that can contain more dictionaries) to menu" children = item.pop('children', []) subMenu = menu.addSubMenu(**item) # we expect item={'text': ...} for child in children: add(subMenu, child) # add recursively to sub-menu # Read menus from users' config file. cp = ConfigParser() cp.optionxform = str # keep case (stackoverflow.com/questions/1611799) protocols = OrderedDict() try: assert cp.read(protocolsConf) != [], 'Missing file %s' % protocolsConf # Populate the protocol menu from the config file. for menuName in cp.options('PROTOCOLS'): menu = ProtocolConfig(menuName) children = json.loads(cp.get('PROTOCOLS', menuName)) for child in children: add(menu, child) protocols[menuName] = menu return protocols except Exception as e: import traceback traceback.print_exc() sys.exit('Failed to read settings. The reported error was:\n %s\n' 'To solve it, delete %s and run again.' % (e, protocolsConf))
def get_lines(self): known = set() for user, plainfile in self.get_files(): try: with open(plainfile) as infile: for line in infile.readlines(): line = line.strip() if line.startswith('#'): continue try: int(line) continue except Exception: pass line = ' '.join(x for x in line.split() if x) if line not in known: yield user, line known.add(line) except Exception: pass for user, histfile in homes.users(file='.local/share/mc/history'): parser = ConfigParser() try: parser.read(histfile) except Exception: continue try: for i in parser.options('cmdline'): line = parser.get('cmdline', i) if line not in known: yield user, line known.add(line) except Exception: pass