Example #1
0
File: media.py Project: sduro/media
def main():
    config = ConfigParser()
    config.read("config/config.cfg")
    # Cantidad de secciones
    sections = config.sections() 
    print("%d secciones:" % len(sections))
# Imprimimos cada una de ellas
    for section in sections:
        print(section)
# Leemos la cantidad de temas
    themes_count = config.getint("general", "temas")
    print(themes_count, type(themes_count))
    for section in config.sections():
        print("\n[%s]" % section)
        for item in config.items(section):
            print(item[0], ":", item[1])
            if(item[0] == "path_origen"):
                print (">>>",item[1],"<<<")
                move_files(str(item[1]).replace('"', '')) #Elimina las comillas del path
                
                # Modificamos el tema principal
            config.set("general", "temas", themes_count + 1)
    # Agregamos un nuevo tema (sección)
    #config.add_section("TEMA3")
    config.set("videos", "nom", "listado pelis")
    # Removemos el ítem "votos" de la sección "TEMA2"
    #config.remove_option("TEMA2", "votos")
    # Guardamos los cambios
    with open("config.cfg", "w") as f:
        config.write(f)
Example #2
0
class Ini():
    """
    Module to read ini files to a dictionary

    Future, develop to write to ini files
    """

    def __init__(self, filename):
        self.settings = ConfigParser()
        self.settings.read(filename)
        if len(self.settings.sections()) == 0:
            raise IOError("Could not open ini file: %s" % (filename, ))

    def read(self):
        """
        'Read' returns a dictionary with the contents of the ini file nominated at class initiation
        """
        output = {}
        sections = self.settings.sections()
        for section in sections:
            options = self.settings.options(section)
            output[section] = {}
            for option in options:
                output[section][option] = self.settings.get(section, option)
        return output

    def write(self):
        """
        'Write' function not yet implemented
        """
        pass
Example #3
0
def parse_config():
    """Function to parse the config file."""
    config_file = glob.glob('config.ini')
    parser = ConfigParser()
    if config_file:
        print 'Found a config file in working directory'
        parser.read(config_file)
        try:
            if 'Logging' in parser.sections():
                log_dir = parser.get('Logging', 'log_file')
            else:
                log_dir = ''
            if 'Auth' in parser.sections():
                auth_db = parser.get('Auth', 'auth_db')
                auth_user = parser.get('Auth', 'auth_user')
                auth_pass = parser.get('Auth', 'auth_pass')
            else:
                auth_db = ''
                auth_user = ''
                auth_pass = ''
            collection = parser.get('Database', 'collection_list')
            whitelist = parser.get('URLS', 'file')
            sources = parser.get('URLS', 'sources').split(',')
            pool_size = int(parser.get('Processes', 'pool_size'))
            return collection, whitelist, sources, pool_size, log_dir, auth_db, auth_user, auth_pass
        except Exception, e:
            print 'Problem parsing config file. {}'.format(e)
Example #4
0
class IniDict(UserDict,object):
	_getformater=None
	_setformater=None
	def __init__(self,fp='',encoding='utf-8'):
		UserDict.__init__(self)
		self.cp=ConfigParser()
		self.path=fp
		self.encoding=encoding
		if fp:self.load(self.path)
	def load(self,p=''):
		if not p:p=self.path
		self.cp.read(p)
		self.update(dict(map(lambda i:(i,dict(self.cp.items(i))),self.cp.sections())))
		if self._getformater:
			for i in self.keys():
				for j in self[i]:
					self[i][j]=self._getformater(self[i][j])
	def save(self,p=''):
		if not p:p=self.path
		for i in self.keys():
			if i not in self.cp.sections():
				i.add_section(i)
			for j in self[i].keys():
				if self._setformater:self.cp.set(i,j,self._setformater(self[i][j]))
				else:cp.set(i,j,self[i][j])
		self.cp.write(open(p,"w"))
	def addGetFormater(self,func):
		if self._getformater:self._getformater=lambda s:func(self._getformater(s))
		else:self._getformater=func
		self.load()
	def addSetFormater(self,func):
		if self._setformater:self._setformater=lambda s:self._setformater(func(s))
		else:self._setformater=func
		self.save()
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
Example #6
0
class Config():
    '''配置文件解析器'''
    def __init__(self, cfgfile):
        pass
        self.cfg = ConfigParser()
        self.cfg.read(cfgfile)
        self._parse()
    def _get_section(self):
        sections = self.cfg.sections()
        return sections
    def _get_option(self, sec):
        return self.cfg.options(sec)
    def _parse(self):
        sections = self.cfg.sections()
        programs = {}
        for sec in sections:
            if sec.startswith('program'):
                try:
                    pname = sec.split(':')[1] 
                    pmodule = self.cfg.get(sec,'module')
                    pclass= self.cfg.get(sec,'class')
                    pmodule_path= self.cfg.get(sec,'module_path')
                    programs[pname] = {'module': pmodule, 'class': pclass, 'module_path':pmodule_path}
                except Exception, e:
                    print e
                    pass
            elif sec == "general":
                try:
                    pidpath= self.cfg.get(sec, 'pidpath')
                    self.pidpath = pidpath
                except Exception, e: 
                    self.pidpath = "/var/tmp"
                    print e
Example #7
0
def test_crud():
    report = crudminer.analyze_dir(TESTDIR, CRUDFILE, True)

    results = []
    for (path, crudp, state, foundver) in report:
        results.append((crudp.name, crudp.secure, state, foundver))

    crudcfg = ConfigParser()
    crudcfg.read(CRUDFILE)

    testcfg = ConfigParser()
    testcfg.read(TESTDIR + '/test.ini')

    for section in crudcfg.sections():
        yield check_sections, section, testcfg.sections()

        if section not in testcfg.sections():
            continue

        secure  = crudcfg.get(section, 'secure')
        failver = testcfg.get(section, 'failver')

        testlist = (section, secure, 'vulnerable', failver)

        yield compare_results, testlist, results

        # pop it from the result, so matches are faster
        results.remove(testlist)
Example #8
0
class Settings(object):
    def __init__(self, settings_file=get_config_file()):
        self.config = ConfigParser()
        self.config.read(settings_file)

    def _get_section_settings(self, section):
        if section not in self.config.sections():
            return None
        else:
            section_settings = {}
            options = self.config.options(section)
            for option in options:
                value = self.config.get(section, option)
                if value[0] == '(' and value.__len__() > 1:
                    value = value.replace("(", "").\
                        replace(")", "").\
                        replace("\'", "")
                    value = tuple(value.split(", "))
                if value == "None":
                    value = None
                section_settings[option] = value
            return section_settings

    def __getattr__(self, name):
        if name in self.config.sections():
            return self._get_section_settings(name)
        else:
            return self.config.sections()
Example #9
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
    def init_server():
        logger = logging.getLogger('EucaAggregate')
        fileHandler = logging.FileHandler('/var/log/euca.log')
        fileHandler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        logger.addHandler(fileHandler)
        fileHandler.setLevel(logging.DEBUG)
        logger.setLevel(logging.DEBUG)

        configParser = ConfigParser()
        configParser.read(['/etc/sfa/eucalyptus_aggregate.conf', 'eucalyptus_aggregate.conf'])
        if len(configParser.sections()) < 1:
            logger.error('No cloud defined in the config file')
            raise Exception('Cannot find cloud definition in configuration file.')
    
        # Only read the first section.
        cloudSec = configParser.sections()[0]
        AggregateManagerEucalyptus.cloud['name'] = cloudSec
        AggregateManagerEucalyptus.cloud['access_key'] = configParser.get(cloudSec, 'access_key')
        AggregateManagerEucalyptus.cloud['secret_key'] = configParser.get(cloudSec, 'secret_key')
        AggregateManagerEucalyptus.cloud['cloud_url']  = configParser.get(cloudSec, 'cloud_url')
        cloudURL = AggregateManagerEucalyptus.cloud['cloud_url']
        if cloudURL.find('https://') >= 0:
            cloudURL = cloudURL.replace('https://', '')
        elif cloudURL.find('http://') >= 0:
            cloudURL = cloudURL.replace('http://', '')
        (AggregateManagerEucalyptus.cloud['ip'], parts) = cloudURL.split(':')
    
        # Create image bundles
        images = self.getEucaConnection().get_all_images()
        AggregateManagerEucalyptus.cloud['images'] = images
        AggregateManagerEucalyptus.cloud['imageBundles'] = {}
        for i in images:
            if i.type != 'machine' or i.kernel_id is None: continue
            name = os.path.dirname(i.location)
            detail = {'imageID' : i.id, 'kernelID' : i.kernel_id, 'ramdiskID' : i.ramdisk_id}
            AggregateManagerEucalyptus.cloud['imageBundles'][name] = detail
    
        # Initialize sqlite3 database and tables.
        dbPath = '/etc/sfa/db'
        dbName = 'euca_aggregate.db'
    
        if not os.path.isdir(dbPath):
            logger.info('%s not found. Creating directory ...' % dbPath)
            os.mkdir(dbPath)
    
        conn = connectionForURI('sqlite://%s/%s' % (dbPath, dbName))
        sqlhub.processConnection = conn
        Slice.createTable(ifNotExists=True)
        EucaInstance.createTable(ifNotExists=True)
        Meta.createTable(ifNotExists=True)
    
        # Start the update process to keep track of the meta data
        # about Eucalyptus instance.
        Process(target=AggregateManagerEucalyptus.updateMeta).start()
    
        # Make sure the schema exists.
        if not os.path.exists(AggregateManagerEucalyptus.EUCALYPTUS_RSPEC_SCHEMA):
            err = 'Cannot location schema at %s' % AggregateManagerEucalyptus.EUCALYPTUS_RSPEC_SCHEMA
            logger.error(err)
            raise Exception(err)
Example #11
0
    def setconfig(self,opts,option_value):
        config_default_file = "%s/%s" % (config_default_dir,self.configName)
        config_def = ConfigParser()
        config_def.read(config_default_file)
        config2 = ConfigParser()
        config2.read(self.config)
        secs = config_def.sections()
        secs_have = config2.sections()
        for sec in secs:
            kvs = config_def.items(sec)
            if sec not in secs_have:
                config2.add_section(sec)
		secs_have.append(sec)
            for value in kvs:
                config2.set(sec,value[0],value[1])
        if opts:
            if "input" not in secs_have:
                config2.add_section("input")
		secs_have.append("input")
            for value in opts:
                if value[0] != "output_dir":
                    config2.set("input",value[0],value[1])
                else:
                    config2.set("input","input_dir",value[1])
        for key,value in option_value.items():
            if "param" not in secs_have:
                config2.add_section("param")
		secs_have.append("param")
            config2.set("param",key,value)
        if "output" not in secs_have:
            config2.add_section("output")
	    secs_have.append("output")
        config2.set("output","output_dir",self.path)
        config2.write(open(self.config,mode="w"))
	def getInstance(cls, application, connection, *args, **kwargs):

		parser = ConfigParser()
		parser.read(cls.getApplicationConfig(application, 'connections.conf'))

		# if alias, resolve alias
		if connection not in parser.sections():
			for section in parser.sections():
				try:
					if connection in (i.strip() for i in parser.get(section, 'aliases').split(',')):
						connection = section
						break
				except NoOptionError:
					pass

		provider = parser.get(connection, 'provider')

		driver = lang.import_module_relative(provider, __name__, 'driver').DbiDriver

		data = {
			'host'       : parser.get(connection, 'host'    ),
			'database'   : parser.get(connection, 'dbname'  ),
			'user'       : parser.get(connection, 'username'),
			'password'   : parser.get(connection, 'password'),
			'_encoding_' : parser.get(connection, 'encoding'),
		}
		try:
			data['port'] = parser.get(connection, 'port')
		except:
			pass

		return driver(application, data, *args, **kwargs)
Example #13
0
def main(args=None):
    '''
    Main entrypoint for this application
    '''
    # Parse command line arguments
    args, parser = parse_commandline_arguments(args)
    args.config = os.path.abspath(os.path.expanduser(args.config))

    # Setup logging
    logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO,
                        format='%(levelname)s: %(message)s')

    # Create a configuration file if it does not exist
    if not os.path.exists(args.config):
        log.warn('Creating config file because it does not exist: {0}'.format(args.config))
        with open(args.config, 'w') as file:
            file.write(DEFAULT_SECTION.format(display=os.environ.get('DISPLAY', ':0')))

    # Read profile configuration
    config = ConfigParser()
    config.read(args.config)

    log.debug('Read xrandr profile information from: {0}'.format(args.config))
    log.debug('Found {0} known profiles: {1}'.format(len(config.sections()),
                                                   config.sections()))
    return args.func(args, config=config)
Example #14
0
def read_config():
  config = ConfigParser()
  if not config.read(config_file):
    raise AutoConnException('ConfigFileError', 'Configuration file missing.')
  elif 'ddns' not in config.sections():
    raise AutoConnException('ConfigFileError', 'Missing section `ddns`.')
  elif 'connect' not in config.sections():
    raise AutoConnException('ConfigFileError', 'Missing section `connect`.')
  return config
Example #15
0
def load_config(config_file):
    parser = ConfigParser()
    parser.read(config_file)
    parser.sections()
    for section in parser.sections():
        add_host(section, parser.get(section, 'ip'))
        # os.system('./add_host.sh {} {}'.format(section, parser.get(section, 'ip')))
        parser.remove_option(section, 'ip')
        for service, command in parser.items(section):
            add_service_to_host(section, service, command)
Example #16
0
class Config(object):
    """ handle to captive portal config (/usr/local/etc/captiveportal.conf)
    """
    _cnf_filename = "/usr/local/etc/captiveportal.conf"

    def __init__(self):
        """ consctruct new config object
        """
        self.last_updated = 0
        self._conf_handle = None
        self._update()

    def _update(self):
        """ check if config is changed and (re)load
        """
        mod_time = os.stat(self._cnf_filename)[stat.ST_MTIME]
        if os.path.exists(self._cnf_filename) and self.last_updated != mod_time:
            self._conf_handle = ConfigParser()
            self._conf_handle.read(self._cnf_filename)
            self.last_updated = mod_time

    def get_zones(self):
        """ return list of configured zones
            :return: dictionary index by zoneid, containing dictionaries with zone properties
        """
        result = dict()
        self._update()
        if self._conf_handle is not None:
            for section in self._conf_handle.sections():
                if section.find('zone_') == 0:
                    zoneid = section.split('_')[1]
                    result[zoneid] = dict()
                    for item in self._conf_handle.items(section):
                        result[zoneid][item[0]] = item[1]
                    # convert allowed(MAC)addresses string to list
                    if 'allowedaddresses' in result[zoneid] and result[zoneid]['allowedaddresses'].strip() != '':
                        result[zoneid]['allowedaddresses'] = \
                            map(lambda x: x.strip(), result[zoneid]['allowedaddresses'].split(','))
                    else:
                        result[zoneid]['allowedaddresses'] = list()
                    if 'allowedmacaddresses' in result[zoneid] and result[zoneid]['allowedmacaddresses'].strip() != '':
                        result[zoneid]['allowedmacaddresses'] = \
                            map(lambda x: x.strip(), result[zoneid]['allowedmacaddresses'].split(','))
                    else:
                        result[zoneid]['allowedmacaddresses'] = list()
        return result

    def fetch_template_data(self, zoneid):
        """ fetch template content from config
        """
        for section in self._conf_handle.sections():
            if section.find('template_for_zone_') == 0 and section.split('_')[-1] == str(zoneid):
                if self._conf_handle.has_option(section, 'content'):
                    return self._conf_handle.get(section, 'content')
        return None
Example #17
0
    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)
Example #18
0
def readConstraintsFile(staff_file):
    """Retrieve staff constraints from staff config file."""

    parser = ConfigParser()
    parser.readfp(staff_file)

    staffList = []
    for staffName in parser.sections():
        if staffName == "General":
            continue

        if parser.has_option(staffName, "canworkweekdays"):
            strList = parser.get(staffName, "canworkweekdays").split()
            canWorkWeekdays = [int(s) for s in strList]
        else:
            canWorkWeekdays = range(7)

        if parser.has_option(staffName, "fixedShifts"):
            fixed = parser.getboolean(staffName, "fixedShifts")
        else:
            fixed = False

        cantWorkDates = []
        if parser.has_option(staffName, "cantworkdates"):
            strList = parser.get(staffName, "cantworkdates").split(',')
            for dateRangeStr in strList:
                dateRange = dateRangeStr.split('to')
                if len(dateRange) == 1:
                    thisdate = datetime.strptime(dateRange[0].strip(), "%d/%m/%y")
                    cantWorkDates.append(thisdate)
                else:
                    startDate = datetime.strptime(dateRange[0].strip(), "%d/%m/%y")
                    endDate = datetime.strptime(dateRange[1].strip(), "%d/%m/%y")
                    nDays = (endDate-startDate).days+1
                    dates = [startDate + timedelta(i) for i in range(nDays)]
                    cantWorkDates.extend(dates)

        staffList.append(Employee(staffName,
                                  canWorkWeekdays=canWorkWeekdays,
                                  cantWorkDates=cantWorkDates,
                                  fixed=fixed))


    if ("General" not in parser.sections()) or not parser.has_option("General", "shiftsPerDay"):
        print "Error: Shifts per day not specified in constraints file."
        exit(1)

    shiftsPerDay = [int(s) for s in parser.get("General", "shiftsPerDay").split()]

    return staffList, shiftsPerDay
    def __Logger_cache_options(self):
        """ **(private)** Read and cache debug levels for categories from config file. """
        configfilename = self.__Logger_find_config()

        if (configfilename != ""):
            parser = ConfigParser()
            parser.read(configfilename)

            for i in range(len(parser.sections())):
                section = parser.sections()[i]
                if (section != SECTION_DEFAULT):
                    instance = self.get_instance(section)
                    self.__Logger_set_instance_options(parser, section, instance)
        return TRUE
Example #20
0
def assertProfilesEqual(profile_filename_a, profile_filename_b,
                        skip_sections=None, skip_options=None):
    """
    Compares two profiles
    """
    if skip_options is None:
        skip_options = {'local_ip_address', 'description', 'name'}

    if skip_sections is None:
        skip_sections = {'target'}

    original = ConfigParser()
    original.read(profile_filename_a)

    saved = ConfigParser()
    saved.read(profile_filename_b)

    #
    #   Analyze in one way
    #
    for section_name in original.sections():
        for orig_name, orig_value in original.items(section_name):
            if orig_name in skip_options:
                continue

            if section_name in skip_sections:
                continue

            saved_value = saved.get(section_name, orig_name)
            msg = ('The "%s" option of the "%s" section changed from'
                   ' "%s" to "%s"')
            args = (orig_name, section_name, orig_value, saved_value)
            assert saved_value == orig_value, msg % args

    #
    #   And then the other
    #
    for section_name in saved.sections():
        for saved_name, saved_value in saved.items(section_name):
            if saved_name in skip_options:
                continue

            if section_name in skip_sections:
                continue

            orig_value = original.get(section_name, saved_name)
            msg = ('The "%s" option of the "%s" section changed from'
                   ' "%s" to "%s"')
            args = (saved_name, section_name, orig_value, saved_value)
            assert saved_value == orig_value, msg % args
Example #21
0
    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
Example #22
0
class CReader(object):
    '''
    Simple config file reader
    '''


    def __init__(self,fn):
        '''
        Constructor
        '''
        self.fn = fn
        self.cp = ConfigParser()
        self.cp.read(fn)
    
     
    def listSections(self):
        return self.cp.sections()
    
    def hasSection(self,secname):
        return secname in self.getSections()
    
    def getSections(self):
        return self.cp.sections()
    
    def _readSec(self,sec,opts):
        ovdic = {}
        for o in opts:
            try:
                val = self.cp.get(sec,str(o))
            except NoSectionError:
                print 'No Sec',sec
                raise
            except NoOptionError as noe:
                print 'No Opt',str(o)
                raise
            ovdic[str(o)] = val
        return ovdic
        
    def readHDSection(self,secname):
        return self._readSec(secname,('header','data'))
    
    def readUPSection(self,secname):
        return self._readSec(secname,('user','pass'))
    
    def readArcGISSection(self,secname):
        return self._readSec(secname,('uname','sname','ctype','desc','cats','url','opts','scan'))
    
    def readSecOpt(self,sec,opt):
        return self.cp.get(sec, opt)
Example #23
0
class BaseDropbox(object):

  def __init__(self):
    APP_KEY = 'oqnyxvnwr67ebpc'
    APP_SECRET = 'd5qiseh1lnfzayh'
    CONFIG_PATH = '~/.dbxrc'

    self.parser = ConfigParser()
    self.path = path.expanduser(CONFIG_PATH)
    if path.exists(self.path):
      self.parser.read(self.path)

    if 'auth' not in self.parser.sections():
      self.parser.add_section('auth')

    if 'general' not in self.parser.sections():
      self.parser.add_section('general')
      self.parser.set('general', 'home', 'Dropbox')

    if self.parser.has_option('auth', 'token'):
      access_token = self.parser.get('auth', 'token')

    else:

      auth_flow = DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET)
      authorize_url = auth_flow.start()
      print "1. Go to: " + authorize_url
      print "2. Click \"Allow\" (you might have to log in first)."
      print "3. Copy the authorization code."
      auth_code = raw_input("Enter the authorization code here: ").strip()

      try:
        access_token, user_id = auth_flow.finish(auth_code)
        print 'Authenticated user: %s' % user_id
      except rest.ErrorResponse, e:
        print('Error: %s' % (e,))
        return

      self.parser.set('auth', 'token', access_token)

    with open(self.path, 'w') as writer:
      self.parser.write(writer)

    self.client = DropboxClient(access_token)
    self.manager = DatastoreManager(self.client)
    self.datastore = self.manager.open_default_datastore()

    self.commit_table = self.datastore.get_table('commit_table')
Example #24
0
class SecretSanta(object):
    
    def __init__(self, config):
        log.debug("Constructing SecretSanta main object.")
        self.people = []
        self.givers = []
        self.receivers = []
        self.pcfile = config.get('global','peopleconf')
        log.debug("Peopleconf is %s" % self.pcfile)
        self.pc=ConfigParser()
        self.pc.read(self.pcfile)
        for sect in self.pc.sections():
            p = SecretSantaPerson(sect, self.pc)
            self.people.append(p)
        for p in self.givers:
            self.receivers.append(p)
        
    
    def matchall(self):
        '''
        Perform matching for all people with constraints. 
        '''
        
        rlist = []
        for p in self.people:
            rlist.append(p)
        shuffle(rlist)
        
        log.debug("Performing matching...")
        for p in self.people:
            r = rlist.pop()
            while not p.matchok(r):
                rlist.append(r)
                shuffle(rlist)
                r = rlist.pop()
            p.receiver = r        
            log.debug("%s -> %s\n" % (p.name, p.receiver.name))
    
    def list(self):
        '''
        Return string representation of all people in config.
        '''
        log.debug("List all users...")
        s = ""
        for p in self.people:
            s+= str(p)
        return s    
    
    def giverslist(self):
        '''
        Return string in form of: 
        Joe Bloe -> Mary Margaret
        Mary Margaret -> Susan Strong
        Susan Strong -> Joe Bloe
        
        '''
        s = ""
        for p in self.people:
            s+= "%s -> %s\n" % ( p.name, p.receiver.name)
        return s
Example #25
0
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
Example #26
0
 def get_mapping_fields(self, cr, uid, shop_id, context=None, reverse=False):
                         
     result = {}
     
     if not context:
         context = {}
         
     shop_pool = self.pool.get('sale.shop')
     shop_data = shop_pool.read(cr, uid, shop_id,
                                ['prestashop_config_path'])
     
     if not shop_data['prestashop_config_path'] or  \
        not shop_data['prestashop_config_path'].endswith(".conf") or\
        not self._prestashop:
         
         return result,False
     
     config = ConfigParser()
     config.read(shop_data['prestashop_config_path'])
     
     if not self._name in config.sections():
         return result,False
     
     mapping = dict(config.items(self._name))
     
     return eval(mapping.get('type_mapping',"[]"))
Example #27
0
def process_config(directory, config_file, sp):
	
	config = ConfigParser()
	config.read(config_file)
	sections = config.sections()
	
	db_or_element = db_or_element_format(sp, sections)
	
	if db_or_element == "db":
		invalid_sections = fc.invalid_config_sections(directory, config_file, sp.full_header_data("db"))
	elif db_or_element == "element":
		invalid_sections = fc.invalid_config_sections(directory, config_file, sp.full_header_data("element"))
	else:
		return "error"

	for s in sections:
		fname = config.get(s, "file_name")
		header = config.get(s, "header")
		if s in invalid_sections:
			if os.path.exists(directory + fname):
				os.remove(directory + fname)
		else:
			with open(directory + s + "_temp.txt", "w") as w:
				w.write(header + "\n")
				with open(directory + fname, "r") as r:
					for line in r:
						w.write(line)
				os.remove(directory + fname)
			os.rename(directory + s + "_temp.txt", directory + fname)
	os.remove(config_file)
	if len(invalid_sections) == 0:
		return None
	return {"invalid_sections":invalid_sections}
Example #28
0
 def startService(self):
     BaseUpstreamScheduler.startService(self)
     log.msg("starting l10n scheduler")
     if self.inipath is None:
         # testing, don't trigger tree builds
         return
     # trigger tree builds for our trees, clear() first
     cp = ConfigParser()
     cp.read(self.inipath)
     self.trees.clear()
     _ds = []
     for tree in cp.sections():
         # create a BuildSet, submit it to the BuildMaster
         props = properties.Properties()
         props.update({
                 'tree': tree,
                 'l10nbuilds': self.inipath,
                 },
                      "Scheduler")
         bs = buildset.BuildSet([self.treebuilder],
                                SourceStamp(),
                                properties=props)
         self.submitBuildSet(bs)
         _ds.append(bs.waitUntilFinished())
     d = defer.DeferredList(_ds)
     d.addCallback(self.onTreesBuilt)
     self.waitOnTree = d
Example #29
0
 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)
Example #30
0
 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()