Example #1
0
    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")
Example #2
0
    def _convert(self):
        from ConfigParser import ConfigParser
        cp=ConfigParser()
        cp.read(self.filename)
        for section in [ 'main', 'default' ]:
            if cp.has_section( section ):
                for key, val in cp.items(section):
                    key = key.lower().replace('_', '')
                    self.repo_cfg[ "%s.%s" % (section, key) ] = val

        for section in filter( lambda n: n.startswith('store '),
                               cp.sections() ):
            for key, val in cp.items(section):
                key = key.lower().replace('_', '')
                self.repo_cfg[ "store.%s.%s" % (section[6:].strip(' "'), key) ] = val
            if not self.repo_cfg.has_key( "store.%s.enabled" % section[6:].strip(' "') ):
                self.repo_cfg[ "store.%s.enabled" % section[6:].strip(' "') ] = "true"

        tmpfile = "%s.%d.%s" % ( self.filename, os.getpid(), ".tmp" )
        try:
            self.save( tmpfile )
            os.rename( tmpfile, self.filename )
        except:
            os.unlink( tmpfile )
            raise
Example #3
0
    def _reload_options(self):
        try:
            self.ctime = os.stat(self.cpath).st_mtime
            cfg = ConfigParser()
            cfg.read(self.cpath)
        except OSError:
            raise ConfigFileNotFoundError(self.cpath, source="default config")

        sections = cfg.sections()

        if len(sections) < 1:
            raise ImproperConfigFileError(self.cpath, _(u"%s should have at least one section" % self.cpath))

        options = Struct()
        options.main = mainsect = dict(cfg.items("main"))
        options.sections = sections

        ## 		if not(options.has_key("module") ^ options.has_key("path")):
        ## 			raise ImproperConfigFileError(self.cpath,
        ## 					_(u"%s should have a ``module`` or ``path`` option, but not both" % self.cpath))

        if not (mainsect.has_key("module") ^ mainsect.has_key("path")):
            raise ImproperConfigFileError(
                self.cpath, _(u"%s should have a ``module`` or ``path`` option, but not both" % self.cpath)
            )

        for sectname in sections[1:]:
            options[sectname] = dict(cfg.items(sectname))

        self.hotplug = mainsect.get("hotplug", False)
        self.module = mainsect.get("module", None)
        self.mpath = mainsect.get("path", "")
        self.class_ = mainsect.get("class", "")

        return options
Example #4
0
def _get_args():
    try:  # py2
        from ConfigParser import ConfigParser
    except ImportError:  # py3
        from configparser import ConfigParser

    args = docopt.docopt(__doc__,
                         version=seltest.__version__,
                         argv=sys.argv[1:])

    config_path = args['--config'] or _find_config()
    config = {}
    profile_config = {}
    if config_path:
        config_path = _expand_path(config_path)
        # allow_no_value so we can write `-v`, not `-v=True`
        cp = ConfigParser(allow_no_value=True)
        cp.read(config_path)
        # this allows -v to mean -v=True, not -v=None
        config = dict((key, True if value is None else value)
                      for key, value in cp.items('default'))
        profile_name = args['--config-profile']
        if profile_name:
            profile_config = dict((key, True if value is None else value)
                                  for key, value in cp.items(profile_name))

    config = _merge_config_dicts(config, DEFAULTS)
    config = _merge_config_dicts(profile_config, config)
    config = _merge_config_dicts(args, config)
    return config
 def read_file(self):
     self.validate_config()
     config = ConfigParser()
     config.read(self.hosts_file)
     sections = config.sections()
     host_store = {}
     self.logger.debug("Extracting all List sections if mandatory, and store "
         "it in host_store as a List with key value as list section_name")
     for section_name in self.list_sections:
         if section_name in sections:
             count = config.getint(section_name, TOTAL_KEY)
             try:
                 prefix = config.get(section_name, PREFIX_KEY)
             except NoOptionError:
                 prefix = section_name
             try:
                 postfix = config.get(section_name, POSTFIX_KEY)
             except NoOptionError:
                 postfix = ''
             host_store[section_name] = []
             for index in range(count):
                 index = index + 1
                 child_section = '%s%s%s' % (prefix, index, postfix)
                 items = config.items(child_section)
                 host_store[section_name].append(dict(items))
                 sections.remove(child_section)
             sections.remove(section_name)
     self.logger.debug("Extracting all other configurations from file and "
         "store it as a dictionary with key value as section_name")
     for section_name in sections:
         items = config.items(section_name)
         host_store[section_name] = dict(items)
     return host_store
Example #6
0
def read_cfg(floc, cfg_proc=process_cfg):
    """
    Reads the given configuration file, returning a dict with the converted values supplemented by default values.

    :param floc: The location of the file to read.
    :param cfg_proc: The processor to use for the raw configuration values.  Uses default values when the raw
        value is missing.
    :return: A dict of the processed configuration file's data.
    """
    config = ConfigParser()
    try:
        good_files = config.read(floc)
    except ParsingError as e:
        raise InvalidDataError(e)
    if not good_files:
        raise IOError('Could not read file {}'.format(floc))
    main_proc = cfg_proc(dict(config.items(MAIN_SEC)), DEF_CFG_VALS, REQ_KEYS, int_list=False)
    # Check that there is a least one subsection, or this script won't do anything. Check that all sections given
    # are expected or alert user that a given section is ignored (thus catches types, etc.)
    no_work_to_do = True
    for section in config.sections():
        if section in SECTIONS:
            if section in SUB_SECTIONS:
                if len(config.items(section)) > 0:
                    no_work_to_do = False
        else:
            warning("Found section '{}', which will be ignored. Expected section names are: {}"
                    .format(section, ", ".join(SECTIONS)))
    if no_work_to_do:
        warning("No filtering will be applied as no criteria were found for the expected subsections ({})."
                "".format(", ".join(SUB_SECTIONS)))
    for section in [MAX_SEC, MIN_SEC]:
        main_proc[section] = check_vals(config, section)
    main_proc[BIN_SEC] = get_bin_data(config, BIN_SEC)
    return main_proc
    def parse_image_build_config(self, config_file_name):

        # Logic taken from koji.cli.koji.handle_image_build.
        # Unable to re-use koji's code because "cli" is not
        # a package of koji and this logic is intermingled
        # with CLI specific instructions.

        args = []
        opts = {}

        config = ConfigParser()
        config.readfp(self.get_default_image_build_conf())
        config.read(config_file_name)

        if self.architectures:
            config.set('image-build', 'arches', ','.join(self.architectures))
        elif self.architecture:
            config.set('image-build', 'arches', self.architecture)
        # else just use what was provided by the user in image-build.conf

        config_str = StringIO()
        config.write(config_str)
        self.log.debug('Image Build Config: \n%s', config_str.getvalue())

        image_name = None

        section = 'image-build'
        for option in ('name', 'version', 'arches', 'target', 'install_tree'):
            value = config.get(section, option)
            if not value:
                raise ValueError('{} cannot be empty'.format(option))
            if option == 'arches':
                value = [arch for arch in value.split(',') if arch]
            elif option == 'name':
                image_name = value
            args.append(value)
            config.remove_option(section, option)

        for option, value in config.items(section):
            if option in ('repo', 'format'):
                value = [v for v in value.split(',') if v]
            elif option in ('disk_size'):
                value = int(value)
            opts[option] = value

        section = 'ova-options'
        if config.has_section(section):
            ova = []
            for k, v in config.items(section):
                ova.append('{}={}'.format(k, v))
            opts['ova_option'] = ova

        section = 'factory-parameters'
        if config.has_section(section):
            factory = []
            for option, value in config.items(section):
                factory.append((option, value))
            opts['factory_parameter'] = factory

        return image_name, args, {'opts': opts}
Example #8
0
def _create_configs_from_file(filename, cluster_config_dir, wildcards):
    configurations = ConfigParser(allow_no_value=True)
    configurations.read(filename)

    for config_file in configurations.sections():
        logger.info("Updating %s...", config_file)
        # For XML configuration files, run things through XmlConfiguration.
        if config_file.endswith('.xml'):
            XmlConfiguration(
                {item[0]: item[1].format(**wildcards)
                 for item in configurations.items(config_file)}
            ).write_to_file(join(cluster_config_dir, config_file))
        # For everything else, recognize whether a line in the configuration should simply be
        # appended to the bottom of a file or processed in some way. The presence of +++ will
        # lead to the evaluation of the following string through the end of the line.
        else:
            lines = []
            for item in configurations.items(config_file):
                if item[0].startswith('+++'):
                    command = item[0].lstrip('+ ').format(**wildcards)

                    # Yes, we use eval here. This is potentially dangerous, but intention.
                    lines.append(str(eval(command))) # pylint: disable=eval-used
                elif item[0] == "body":
                    lines.append(item[1].format(**wildcards))
                else:
                    lines.append(item[0].format(**wildcards))
            with open(join(cluster_config_dir, config_file), 'w') as conf:
                conf.write("".join(["{0}\n".format(line) for line in lines]))
Example #9
0
def config_from_file(config_file):
    global config
    global template_dirs
    global template_loader
    
    # Read configuration

    here = os.path.abspath('.')

    confp = ConfigParser(defaults={'here': here})
    confp.read(config_file)
    
    for sec in ('stats', 'checkers', 'alerts', 'mailer'):
        config[sec] = dict(confp.items(sec))

    # Setup template loader

    template_dirs = [
        os.path.abspath('./templates')]
    template_loader.search_path.extend(template_dirs)
    
    # Load and register additional checkers
    
    for name, cls_name in confp.items('checkers'):
        if name != 'here':
            cls = _load_checker(name, cls_name)
            logging.info('Loaded checker %s: %r', name, cls)

    return
Example #10
0
    def __init__(self):

        conf = ConfigParser()
        conf.read('conf.ini')
        self.log_url = 'https://xueqiu.com/user/login'
        self.log_data = dict(conf.items('account'))
        self.header = dict(conf.items('header'))
Example #11
0
def parse_config(configs):
    """
    :type configs list
    :rtype: ConfigParser
    """
    conf = ConfigParser()

    all_configs = []
    while len(configs) > 0:
        all_configs += configs
        files = []
        for mask in configs:
            for f in glob.glob(mask):
                if os.path.isfile(f):
                    files.append(f)
        conf.read(files)
        configs = []
        if conf.has_option(DEFAULT_SECTION, "include"):
            configs = list(set(re.split(r'\s+', conf.get(DEFAULT_SECTION, "include"))) - set(all_configs))

    for section in conf.sections():
        for k, v in conf.items(DEFAULT_SECTION):
            if not conf.has_option(section, k):
                conf.set(section, k, v)
        for k, v in conf.items(section):
            v = re.sub(r'^\s*"|"\s*$', '', v) # remove quotes
            conf.set(section, k, v)

    conf.remove_section(DEFAULT_SECTION)

    if not conf.sections():
        usage("No sections found in config files " + ", ".join(all_configs))
    return conf
Example #12
0
class Playlist(object):
  def __init__(self, location):
    dir = os.path.expanduser(os.path.dirname(location))
    if not os.path.exists(dir):
      os.makedirs(dir)

    self._config = ConfigParser()
    self._config.optionxform = str

    self._file = os.path.expanduser(location)
    if os.path.exists(self._file):
      self._config.read(self._file)
    else:
      self._config.add_section('Playlist')
      self.save()

  def save(self):
    self._config.write(open(self._file, 'wb'))

  def append(self, item):
    self._config.set('Playlist', *item)
    self.save()

  def remove(self, option):
    self._config.remove_option('Playlist', option)
    self.save()

  def __getitem__(self, item):
    return self._config.items('Playlist')[item]

  def __iter__(self):
    return iter(self._config.items('Playlist'))
Example #13
0
    def parse_config(self, config_filename):

        if not config_filename:

            config_filename = os.path.join(os.path.dirname(__file__), 'configs', 'default.ini')

        if not os.path.exists(config_filename):

            config_filename = os.path.join(os.path.dirname(__file__), 'configs', config_filename)

            if not os.path.exists(config_filename):

                self.logger.error('Could not open configuration file %s', config_filename)
                sys.exit(1)

        config = ConfigParser()
        config.read(config_filename)

        self.logger.info('Loaded configuration file: %s', config_filename)

        # Parse configuration
        for section in config.sections():

            if section == 'FakeNet':
                self.fakenet_config = dict(config.items(section))

            elif section == 'Diverter':
                self.diverter_config = dict(config.items(section))

            elif config.getboolean(section, 'enabled'):
                self.listeners_config[section] = dict(config.items(section))
Example #14
0
def get_app_info(app_dir, app):
    app_info = {'app_key': app}

    dev_dir = join(app_dir, app, DEVELOP_DIR)
    if isdir(dev_dir) and exists(join(dev_dir, CER_FILE)) \
           and exists(join(dev_dir, KEY_FILE)):
        # 读配置文件
        conf = join(dev_dir, CONF_FILE)
        conf_dict = {}
        if exists(conf):
            config = ConfigParser()
            config.read(conf)
            conf_dict = dict(config.items('apnsagent'))
        app_info['develop'] = {'cer_file': join(dev_dir, CER_FILE),
                               'key_file': join(dev_dir, KEY_FILE),
                               'config': conf_dict}

    pro_dir = join(app_dir, app, PRODUCTION_DIR)
    if isdir(pro_dir) and exists(join(pro_dir, CER_FILE)) \
           and exists(join(pro_dir, KEY_FILE)):
        conf = join(pro_dir, CONF_FILE)
        log.debug('config file: %s' % conf)
        conf_dict = {}
        if exists(conf):
            log.debug('load config file')
            config = ConfigParser()
            config.read(conf)
            conf_dict = dict(config.items('apnsagent'))
            log.debug('config content %s' % conf_dict)
        app_info['production'] = {'cer_file': join(pro_dir, CER_FILE),
                                'key_file': join(pro_dir, KEY_FILE),
                                'config': conf_dict}
    return app_info
Example #15
0
def read_config_file(filename):
    """Return Settings instance built from contents of ``filename`` file."""
    parser = ConfigParser()
    parser.read(filename)
    settings = Settings()
    core_section = 'macman'
    default_section = 'default'
    # Handle core configuration.
    if parser.has_section(core_section):
        section = core_section
        for option in ['directory']:
            if parser.has_option(section, option):
                setattr(settings, option, parser.get(section, option))
    # Handle default configuration.
    if parser.has_section(default_section):
        section = settings.default
        settings.default = dict(parser.items(section))
    # Handle configuration of VMs.
    special_sections = (core_section, default_section)
    for section in parser.sections():
        if section in special_sections:
            continue
        vm_id = section
        settings.vms[vm_id] = dict(parser.items(section))
    return settings
Example #16
0
    def __init__(self):

        conf = ConfigParser()
        conf.read('conf.ini')
        self.url = 'http://mm.taobao.com/json/request_top_list.htm?page='
        self.login_data = dict(conf.items('account'))
        self.headers = dict(conf.items('header'))
        self.ses = requests.session()
Example #17
0
    def __init__(self):

        conf = ConfigParser()
        conf.read('conf.ini')
        self.url = 'http://www.mace.manchester.ac.uk'
        self.login_data = dict(conf.items('account'))
        self.headers = dict(conf.items('header'))
        self.ses = requests.session()
Example #18
0
    def setUp(self):
        self.log("setUp()")
        self.log("test directory="+self.test_dir)

        # 1 read config file and pull out some stuff
        if not os.path.isfile(os.path.join(self.test_dir,'test.cfg')):
            raise ValueError('test.cfg does not exist in test dir')
        config = ConfigParser()
        config.read(os.path.join(self.test_dir,'test.cfg'))
        self.test_cfg = {}
        self.nms_test_cfg = {}
        for entry in config.items('catalog-test'):
            self.test_cfg[entry[0]] = entry[1]
        for entry in config.items('NarrativeMethodStore'):
            self.nms_test_cfg[entry[0]] = entry[1]
        self.log('test.cfg parse\n'+pformat(self.test_cfg))

        # passwords not needed in tests yet
        self.test_user_1 = self.test_cfg['test-user-1']
        #self.test_user_psswd_1 = self.test_cfg['test-user-psswd-1']
        self.test_user_2 = self.test_cfg['test-user-2']
        #self.test_user_psswd_2 = self.test_cfg['test-user-psswd-2']

        # 2 check that db exists and collections are empty
        self.mongo = MongoClient('mongodb://'+self.test_cfg['mongodb-host'])
        db = self.mongo[self.test_cfg['mongodb-database']]
        self.modules = db[MongoCatalogDBI._MODULES]
        self.developers = db[MongoCatalogDBI._DEVELOPERS]
        # just drop the test db
        self.modules.drop()
        self.developers.drop()
        #if self.modules.count() > 0 :
        #    raise ValueError('mongo database collection "'+MongoCatalogDBI._MODULES+'"" not empty (contains '+str(self.modules.count())+' records).  aborting.')

        self.initialize_mongo()

        # 3 setup the scratch space
        self.scratch_dir = os.path.join(self.test_dir,'temp_test_files',str(datetime.now()))
        self.log("scratch directory="+self.scratch_dir)
        os.makedirs(self.scratch_dir)


        # 4 startup any dependencies (nms, docker registry?)


        # 4 assemble the config file for the catalog service
        self.catalog_cfg = {
            'admin-users':self.test_user_2,
            'mongodb-host':self.test_cfg['mongodb-host'],
            'mongodb-database':self.test_cfg['mongodb-database'],
            'temp-dir':self.scratch_dir,
            'docker-base-url':self.test_cfg['docker-base-url'],
            'docker-registry-host':self.test_cfg['docker-registry-host'],
            'nms-url':self.test_cfg['nms-url'],
            'nms-admin-user':self.test_cfg['nms-admin-user'],
            'nms-admin-psswd':self.test_cfg['nms-admin-psswd']
        }
 def validate_config(self):
     config = ConfigParser()
     config.read(self.hosts_file)
     sections = config.sections()
     self.logger.debug("Validating mandatory sections")
     for section_name in self.mandatory_sections:
         if section_name not in sections:
             raise NoSectionError(section_name)
     self.logger.debug("Validating sections to be extracted as list")
     for section_name in self.list_sections:
         if section_name in sections:
             try:
                 count = config.getint(section_name, TOTAL_KEY)
             except NoOptionError:
                 self.logger.error(
                     "'%s' option not specified in mandatory" " list section '%s'" % (TOTAL_KEY, section_name)
                 )
                 raise NoOptionError(TOTAL_KEY, section_name)
             try:
                 prefix = config.get(section_name, PREFIX_KEY)
             except NoOptionError:
                 prefix = section_name
             self.prefix_store[section_name] = prefix
             try:
                 postfix = config.get(section_name, POSTFIX_KEY)
             except NoOptionError:
                 postfix = ""
             self.postfix_store[section_name] = postfix
             for index in range(count):
                 index = index + 1
                 child_section = "%s%s%s" % (prefix, index, postfix)
                 try:
                     config.items(child_section)
                 except NoSectionError:
                     self.logger.error(
                         "'%s' section not specified for"
                         " parent section '%s'. '%s' is a"
                         " list section with count '%s'." % (child_section, section_name, section_name, count)
                     )
                     raise NoSectionError(
                         "'%s' section not specified for"
                         " parent section '%s'. '%s' is a"
                         " list section with count '%s'." % (child_section, section_name, section_name, count)
                     )
                 sections.remove(child_section)
             sections.remove(section_name)
     self.logger.debug("Validating sections are within ths section_schema," " if specified")
     if self.section_schema is not None:
         for section_name in self.section_schema:
             try:
                 sections.remove(section_name)
             except ValueError:
                 pass
         if len(sections) != 0:
             self.logger.error("'Invalid sections added. %s" % (sections))
             raise Error("Invalid sections added. %s" % (sections))
Example #20
0
    def _loadFeatConf(self, location):
        """ Load configuration needed for feature extraction...
        """
        log.debug(unicode(self) + " loading config file at '%s'." % (location))

        with codecs.open(location, encoding="utf-8") as fh:
            featcfp = ConfigParser()
            featcfp.readfp(fh)

        return list(featcfp.items("HCOPY")) + list(featcfp.items("GLOBAL"))
Example #21
0
    def from_ini(cls, fname, args=None):
        print "This function is being deprecated and replaced by from_yaml classmethod"
        config_parse_object = ConfigParser()
        config_parse_object.read(fname)
        general_dict = dict(config_parse_object.items('general'))
        abundance_dict = dict(config_parse_object.items('abundances'))

        config_object = cls()
        config_object.parse_general_section(general_dict)
        config_object.parse_abundance_section(abundance_dict)
        return config_object
Example #22
0
def configure():
    global BUILD_ID, cformat

    # Parse command line arguments
    options, args = parse_args()

    # Load the configuration from the file
    conf = ConfigParser()
    conf.read(options.conf)
    sections = conf.sections()
    if 'global' in sections:
        glow = dict((k.lower(), k) for k in globals())
        for k, v in conf.items('global'):
            key = glow.get(k.lower())
            if key:
                conv = type(globals()[key])  # int or str
                globals()[key] = conv(v)
    if 'output' in sections:
        DEFAULT_OUTPUT.update(conf.items('output'))
    if 'colors' in sections:
        COLOR.update(conf.items('colors'))
    if 'symbols' in sections:
        SYMBOL.update(conf.items('symbols'))
    if 'issues' in sections:
        # Preload the known issues
        for num, val in conf.items('issues'):
            rule = tuple(arg.strip() for arg in val.split(':'))
            issues._preload.append((num, rule))

    # Set timeout
    socket.setdefaulttimeout(DEFAULT_TIMEOUT)

    # Prepare the output colors
    prepare_output()

    # Tweak configuration

    if DEFAULT_FAILURES and not options.failures:
        options.failures = DEFAULT_FAILURES.split()

    if options.failures:
        # ignore the -q option
        options.quiet = 0

    if options.no_color:
        # replace the colorizer
        cformat = _cformat_plain

    if options.id == "build":
        # Use the build number as identifier
        BUILD_ID = "num"

    # out(options, args)
    return options, args
Example #23
0
    def load(cls):
        obj = cls()
        if not config_directory.exists() and not cls.config_file.exists():
            return obj

        cp = ConfigParser()
        cp.read(cls.config_file)

        obj.contacts.update(cp.items("contacts"))
        obj.calendars.update(cp.items("calendars"))

        return obj
def get_config():
    my_dir = os.path.dirname(os.path.realpath(argv[0]))
    my_ini = os.path.join(my_dir, 'steepleherder.ini')

    cp = ConfigParser()
    cp.read(my_ini)

    config = {}
    config['credentials'] = dict(cp.items('Credentials'))
    config['repo'] = dict(cp.items('Repo'))
    config['system'] = dict(cp.items('System'))
    return config
Example #25
0
class UIMapFileHandler:
    def __init__(self, uiMapFiles): 
        self.readFiles(uiMapFiles)

    def readFiles(self, uiMapFiles):
        # See top of file: uses the version from 2.6
        self.writeParsers = map(WriteParserHandler, uiMapFiles)
        if len(self.writeParsers) == 1:
            self.readParser = self.writeParsers[0]
        else:
            self.readParser = ConfigParser(dict_type=OrderedDict)
            self.readParser.optionxform = str # don't automatically lower-case everything
            self.readParser.read(uiMapFiles)

    def storeInfo(self, sectionName, signature, eventName):
        if not self.readParser.has_section(sectionName):
            self.writeParsers[-1].add_section(sectionName)
           
        signature = signature.replace("::", "-") # Can't store :: in ConfigParser unfortunately
        if not self.readParser.has_option(sectionName, signature):
            for writeParser in self.writeParsers:
                if writeParser.has_section(sectionName):
                    writeParser.set(sectionName, signature, eventName)
            
    def findWriteParser(self, section):
        for parser in self.writeParsers:
            if parser.has_section(section):
                return parser

    def updateSectionName(self, section, newName):
        """ Note, we only add a new section, don't delete the old one as we once did
        This is in case some other widget is using it, which is possible and not easily detected currently
        Let the user clean away the old section if they want to."""
        writeParser = self.findWriteParser(section)
        if not writeParser.has_section(newName):
            writeParser.add_section(newName)
        for name, value in self.readParser.items(section):
            writeParser.set(newName, name, value)
        return newName

    def write(self, *args):
        for parserHandler in self.writeParsers:
            parserHandler.write()

    def __getattr__(self, name):
        return getattr(self.readParser, name)

    def findSectionAndOption(self, valueString):
        for section in self.readParser.sections():
            for optionName, value in self.readParser.items(section):
                if value and valueString.startswith(value):
                    return section, optionName
        return None, None
Example #26
0
class ProjectManager(object):
    def __init__(self, mode=None):
        self.options = {}
        self.exePath = ''
        self.configPath = expanduser('~/.laue_script.ini')
        self.config = ConfigParser()
        try:
            self.config.read(self.configPath)
            self.config.items('Projects')
        except NoSectionError:
            self._make_config()
            self.config.read(self.configPath)
        if not mode == 'create':
            self._parseArgs()

    def getProjectsDirectory(self):
        return self.config.get('Projects', 'ProjectPath')

    def projectExists(self, projectName):
        return isdir(self.getProjectsDirectory() + '/{}'.format(projectName))

    def _make_config(self):
        conf = ConfigParser()
        conf.add_section('Projects')
        conf.add_section('Options')
        conf.set('Projects', 'ProjectPath', expanduser('~/Laue-Script/projects'))
        conf.set('Options', '-p', True)
        conf.set('Options', '-v', False)
        conf.set('Options', 'build', False)
        with open(expanduser('~/.laue_script.ini'), 'w') as fp:
            conf.write(fp)

    def _parseArgs(self):
        self.options = {}
        parser = FirstParser(self)
        items = {item[0]: item[1] for item in self.config.items('Options')}
        for string in argv:
            try:
                parser = parser(string, items)
            except ArgParseError:
                print 'Exiting gracefully after argument parsing error.'
                exit()
        try:
            parser.validate()
        except ArgParseError:
            print 'Exiting gracefully...'
            exit()

    def arg(self, string):
        try:
            return self.options[string]
        except KeyError:
            return False
Example #27
0
 def __init__(self, file):
     self.file = file
     if file:
         f = open(file, "r")
         cp = ConfigParser()
         cp.readfp(f)
         f.close()
         self.dict = dict(cp.items("user"))
         if cp.has_section("templates"):
             self.templates = dict(cp.items("templates"))
         else:
             self.templates = dict()
Example #28
0
    def read_config(self, args):
        if len(args) != 2:
            print('Usage: ', args[0], '<config file>')
            sys.exit(1)

        config = ConfigParser()
        config.readfp(open(args[1]))
        drivers = []

        def universes(section):
            d = dict(config.items(section))
            return (d['driver'], d['port'])

        for (driver, port), lights in itertools.groupby(config.sections(), universes):
            if driver == 'dmx':
                fixtures = []
                for light in list(lights):
                    l = dict(config.items(light))
                    fixtures.append(DmxFixture(**l))
                try:
                    d = DriverDmx(fixtures, port=port)
                    drivers.append(d)
                except:
                    print("not adding", port)
            elif driver == 'allpixel':
                light = dict(config.items(list(lights)[0]))
                try:
                    d = DriverSerial(num=int(light['length']),type=getattr(LEDTYPE, light['type']), dev=port)
                    drivers.append(d)
                except:
                    print("not adding", port)
            elif driver == 'emulator':
                light = dict(config.items(list(lights)[0]))
                try:
                    num_pixels = int(math.sqrt(int(light['length'])))
                    d = DriverVisualizer(width=num_pixels, height=num_pixels)
                    drivers.append(d)
                except:
                    print("error adding visualizer")
            elif driver == 'dummy':
                light = dict(config.items(list(lights)[0]))
                print(light)
                try:
                    num_pixels = int(light['length'])
                    d = DriverDummy(num=num_pixels)
                    drivers.append(d)
                except:
                    print("error adding dummy, you dummy")
            elif driver == 'audio':
                light = dict(config.items(list(lights)[0]))
                self.audio_port = int(port)

        return drivers
Example #29
0
def read_config(path=None, section="edwin"):
    if path is None:
        path = get_default_config_file() #pragma NO COVERAGE
    here = os.path.dirname(path)
    config = {}
    parser = ConfigParser({'here': here})
    parser.read([path,])
    for k, v in parser.items('DEFAULT'):
        config[k] = v
    for k, v in parser.items(section):
        config[k] = v
    return config
Example #30
0
def loadConfig(config_file):
    config = ConfigParser()
    config.read(config_file)

    try:
        storage_conf = dict(config.items('storage'))
        style_headers = csv.reader([config.get('worker', 'styles')],skipinitialspace=True).next()

    except Exception as ex:
        print>>sys.stderr,"ERROR: failed to load worker configuration from: %s (%s)" % (config, str(ex))
        sys.exit(1)

    formats = {}
    try:
        formats = dict(config.items('formats'))
	for name, format in formats.iteritems():
            formats[name] = csv.reader([format], skipinitialspace=True).next()

    except Exception as ex:
        print>>sys.stderr,"ERROR: failed to load worker configuration for formats from: %s (%s)" % (config, str(ex))

    styles = {}
    for style_header in style_headers :
        print>>sys.stderr,"Loading '%s' style" % style_header
        try :
            name = config.get(style_header, "type")
            styles[name] = formats[name]
        except Exception as ex:
            print>>sys.stderr,"ERROR: failed to load worker configuration for '%s' from: %s (%s)" % (style_header,config, str(ex))
            sys.exit(1)
    
    renames = {}
    for fmt in set([item for sublist in styles.values() for item in sublist]):
        try:
            opts = dict(config.items(fmt))
            if 'pil_name' in opts:
                renames[fmt] = opts['pil_name']
        except Exception as ex:
            print>>sys.stderr,"ERROR: failed to load worker configuration for format '%s' from: %s (%s)" % (fmt,config, str(ex))
            sys.exit(1)

    for style in styles:
        fmts2 = []
        for fmt in styles[style]:
            if fmt in renames:
                fmts2.append(renames[fmt])
            else:
                fmts2.append(fmt)
        styles[style] = fmts2

    return styles, tile_storage.TileStorage(storage_conf)