Пример #1
0
def saveWebserverSection():
    """
    Save stuff
    """
    section = 'webserver'

    cfg = SafeConfigParser()
    try:
        with codecs.open(autosub.CONFIGFILE, 'r', autosub.SYSENCODING) as f:
            cfg.readfp(f)
    except:
        #no config yet
        cfg = SafeConfigParser()
        pass

    if not cfg.has_section(section):
        cfg.add_section(section)

    cfg.set(section, "webserverip", str(autosub.WEBSERVERIP))
    cfg.set(section, 'webserverport', str(autosub.WEBSERVERPORT))
    cfg.set(section, "username", autosub.USERNAME)
    cfg.set(section, "password", autosub.PASSWORD)
    cfg.set(section, "webroot", autosub.WEBROOT)

    with open(autosub.CONFIGFILE, 'wb') as file:
        cfg.write(file)
Пример #2
0
 def save_project(self, case):
     nunberofdatapersection = [0, len(p4R.s_crystal),
                               len(p4R.s_data_file),
                               len(p4R.s_experiment),
                               len(p4R.s_material),
                               len(p4R.s_strain_DW),
                               len(p4R.s_GSA_options),
                               len(p4R.s_bsplines),
                               len(p4R.s_pv),
                               len(p4R.s_GSA_expert),
                               len(p4R.s_leastsq),
                               len(p4R.s_geometry),
                               len(p4R.s_substrate)]
     a = P4Rm()
     filename_ = a.PathDict['path2inicomplete']
     parser = SafeConfigParser()
     if case == 0:
         parser.read(filename_)
     new_section_name = p4R.Exp_file_all_section
     for i in range(len(p4R.Exp_file_section)):
         if case == 1:
             parser.add_section(p4R.Exp_file_section[i])
         k = nunberofdatapersection[i]
         r = nunberofdatapersection[i+1]
         new_section_name = new_section_name[k:]
         for l in range(r):
             parser.set(p4R.Exp_file_section[i], new_section_name[l],
                        str(a.AllDataDict[new_section_name[l]]))
     parser.write(open(filename_, 'w'))
Пример #3
0
    def _create_configuration(self):
        """
        Create and return ConfigParser object containing the device
        configurations

        Return:
            ConfigParser object containing the configurations
        """
        logging.info("Creating configuration object")
        config = SafeConfigParser()

        device_ids = {}

        for device in self._devices:
            # lack of model generally means that there was an unused power
            # cutter socket
            if not "model" in device:
                continue

            if not device["model"] in device_ids:
                device_ids[device["model"]] = 1

            dev_id = device_ids[device["model"]]
            device_ids[device["model"]] = dev_id + 1

            section = device["model"].upper() + "_" +  str(dev_id)

            config.add_section(section)

            for key in device:
                config.set(section, key, str(device[key]))

        return config
Пример #4
0
def saveLogfileSection():
    """
    Save stuff
    """
    section = 'logfile'

    cfg = SafeConfigParser()
    try:
        with codecs.open(autosub.CONFIGFILE, 'r', autosub.SYSENCODING) as f:
            cfg.readfp(f)
    except:
        #no config yet
        cfg = SafeConfigParser()
        pass

    if not cfg.has_section(section):
        cfg.add_section(section)

    cfg.set(section, "loglevel", logging.getLevelName(int(autosub.LOGLEVEL)).lower())
    cfg.set(section, "loglevelconsole", logging.getLevelName(int(autosub.LOGLEVELCONSOLE)).lower())
    cfg.set(section, "logsize", str(autosub.LOGSIZE))
    cfg.set(section, "lognum", str(autosub.LOGNUM))

    with open(autosub.CONFIGFILE, 'wb') as file:
        cfg.write(file)
Пример #5
0
Файл: cli.py Проект: mgaitan/mts
def get_config():

    DEFAULTS = { 'main': {
                    "player": "mplayer -fs {episode} [-sub {subs}]",
                    },
                }

    config = SafeConfigParser()
    if not os.path.exists(CONFIG_FILE):
        print "There is no config file. Creating default in %s" % CONFIG_FILE
        for section, options in DEFAULTS.items():
            for section, options in DEFAULTS.items():
                if not config.has_section(section):
                    config.add_section(section)
                for option, value in options.items():
                    config.set(section, option, value)

        if not os.path.exists(APP_DATA_DIR):
            os.makedirs(APP_DATA_DIR)   #make .mts dir
        with open(CONFIG_FILE, 'w') as cfg:
            config.write(cfg)
    else:
        with open(CONFIG_FILE, 'r') as cfg:
            config.readfp(cfg)
    return config
Пример #6
0
def zip_files():
    dirs = ['linux', 'windows']
    section = 'CONFIG'

    for item in dirs:

        print item
        src = os.path.abspath(os.path.join(sys.path[0], '..', 'node', item))
        config_path = os.path.abspath(os.path.join(src, 'config.ini'))

        config = SafeConfigParser()
        config.read(config_path)

        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))

        if section not in config.sections():
            config.add_section(section)

        config.set(section, 'port', '5555')
        config.set(section, 'hub_host', socket.gethostname())
        config.set(section, 'hub_ip', s.getsockname()[0])

        with open(config_path, 'w') as f:
            config.write(f)

        try:
            archive = shutil.make_archive(item, 'zip', src)
            shutil.copy(archive, os.path.abspath(os.path.join(sys.path[0], '..', '..', 'files')))
            os.remove(archive)
        except:
            print "Something went wrong while attempting to zip, move or delete %s files." % item.title()
Пример #7
0
def save_persistent_search_path(prefix, path):
    """Save the prefix, path pair. If path is None delete the
    registered prefix.

    """
    if isinstance(path, list):
        path = os.path.pathsep.join(path)

    if prefix == "":
        # Store "" prefix as "__default__"
        prefix = "__default__"

    user_settings_dir = Orange.utils.environ.orange_settings_dir
    if not os.path.exists(user_settings_dir):
        try:
            os.makedirs(user_settings_dir)
        except OSError:
            pass

    filename = os.path.join(user_settings_dir, "orange-search-paths.cfg")
    parser = SafeConfigParser()
    parser.read([filename])

    if not parser.has_section("paths"):
        parser.add_section("paths")

    if path is not None:
        parser.set("paths", prefix, path)
    elif parser.has_option("paths", prefix):
        # Remove the registered prefix
        parser.remove_option("paths", prefix)
    parser.write(open(filename, "wb"))
   def write(self, parmFile):
      """ Write state to param file

      Parameters
      ----------
         parmFile: Name of file to write to 
            
      Returns
      -------
      None
      """
         
      config = SafeConfigParser()

      # When adding sections or items, add them in the reverse order of
      # how you want them to be displayed in the actual file.
      # In addition, please note that using RawConfigParser's and the raw
      # mode of ConfigParser's respective set functions, you can assign
      # non-string values to keys internally, but will receive an error
      # when attempting to write to a file or when you get it in non-raw
      # mode. SafeConfigParser does not allow such assignments to take place.

      config.add_section('latest')

      s = ""
      for f in self._cfs:
         s += f
         s += "\n"
      config.set('latest', 'cfs', s)

      # Write it out
      with open(parmFile, 'wb') as configfile:
         config.write(configfile)
Пример #9
0
def configure(config_file, env):
    config = {}
    conf = SafeConfigParser()
    passwd = None
    if conf.read(config_file):
        config['username'] = conf.get(env, 'username')
        config['dreadnot'] = conf.get(env, 'dreadnot')
        config['region'] = conf.get(env, 'region')
    else:
        config['dreadnot'] = raw_input('Dreadnot URL:')
        config['region'] = raw_input('Deployment region:')
        config['username'] = raw_input('Dreadnot username:'******'dreadnot', 'region', 'username'):
            conf.set(env, name, config[name])
        with open(config_file, 'w') as f:
            conf.write(f)
    if keyring:
        passwd = keyring.get_password('dreadnot', config['dreadnot'])
    if not passwd:
        passwd = getpass.getpass('Dreadnot password:'******'dreadnot', config['dreadnot'], passwd)
    config['password'] = passwd
    return config
Пример #10
0
def saveSkipshowSection():
    """
    Save stuff
    """
    section = 'skipshow'

    cfg = SafeConfigParser()
    try:
        with codecs.open(autosub.CONFIGFILE, 'r', autosub.SYSENCODING) as f:
            cfg.readfp(f)
    except:
        #no config yet
        cfg = SafeConfigParser()
        pass
    
    if cfg.has_section(section):
        cfg.remove_section(section)
        cfg.add_section(section)
        with open(autosub.CONFIGFILE, 'wb') as file:
            cfg.write(file)

    for x in autosub.SKIPSHOW:
        SaveToConfig('skipshow', x, autosub.SKIPSHOW[x])

    # Set all skipshow stuff correct
    applyskipShow()
Пример #11
0
Файл: sr.py Проект: fheinle/SR
def create(directory):
    """
    create a new directory and the subdirectories needed for usage with sr
    
    @param directory: path where to create a new project
    @type directory: string
    """
    os.makedirs(directory)
    os.makedirs(os.path.join(directory, 'source'))
    os.makedirs(os.path.join(directory, 'templates'))
    os.makedirs(os.path.join(directory, 'output'))
    
    config_file = open(os.path.join(directory, 'config.ini'), 'w')
    config = SafeConfigParser()
    config.add_section('markdown')
    config.add_section('general')
    config.set('markdown', 'safe', 'False')
    config.set('markdown', 'addons', ',')
    config.set('general', 'suffix', '.txt')
    config.write(config_file)
    config_file.close()
    standard_template = open(os.path.join(
                                          directory,
                                          'templates',
                                          'standard.html'
                                          ), 'w')
    standard_template.write('<!-- Put your layout here. -->\n$content\n')
    standard_template.close()
    print "Created a new project under %s" % directory
Пример #12
0
def saveUsernamemappingSection():
    """
    Save stuff
    """
    section = 'namemapping'

    cfg = SafeConfigParser()
    try:
        with codecs.open(autosub.CONFIGFILE, 'r', autosub.SYSENCODING) as f:
            cfg.readfp(f)
    except:
        #no config yet
        cfg = SafeConfigParser()
        pass

    if cfg.has_section(section):
        cfg.remove_section(section)
        cfg.add_section(section)
        with open(autosub.CONFIGFILE, 'wb') as file:
            cfg.write(file)

    for x in autosub.USERNAMEMAPPING:
        SaveToConfig('namemapping', x, autosub.USERNAMEMAPPING[x])

    # Set all namemapping stuff correct
    applynameMapping()
Пример #13
0
    def save(self, dir_path):
        """
        save the configuration used for this run in the ini format file
        """
        parser = SafeConfigParser()
        parser.add_section('base')
        parser.set('base', 'file', str(self.options['sequence_db']))
        parser.set('base', 'type', str(self.options['db_type']).lower())
        cfg_opts = [('base', ('replicon_topology', 'topology_file', 'index_db_exe',)),
                    ('system', ('inter_gene_max_space', 'min_mandatory_genes_required', 'min_genes_required', 'max_nb_genes', 'multi_loci')),
                    ('hmmer', ('hmmer_exe', 'e_value_res', 'i_evalue_sel', 'coverage_profile')),
                    ('directories', ('def_dir', 'res_search_dir', 'res_search_suffix', 'profile_dir', 'profile_suffix', 'res_extract_suffix')),
                    ('general', ('log_level', 'log_file', 'worker_nb'))
                    ]

        for section, directives in cfg_opts:
            if not parser.has_section(section):
                parser.add_section(section)
            for directive in directives:
                try:
                    if self.options[directive] is not None:
                        if directive in ('inter_gene_max_space', 'min_mandatory_genes_required', 'min_genes_required', 'max_nb_genes'):
                            s = ''
                            for system, space in self.options[directive].items():
                                s += " {0} {1}".format(system, space)
                            parser.set(section, directive, s)
                        elif directive != 'log_file' or self.options[directive] != os.path.join(self.options['working_dir'], 'macsyfinder.log'):
                            parser.set(section, directive, str(self.options[directive]))
                except KeyError:
                    pass
        with open(os.path.join(dir_path, self._new_cfg_name), 'w') as new_cfg:
            parser.write(new_cfg)
Пример #14
0
class Configuration(object):
    def __init__(self, config_dir):
        self.config_file = os.path.join(config_dir, "settings.cfg")
        self.config = SafeConfigParser()

        if os.path.isfile(self.config_file):
            self.reload()
        else:
            self._setup_config()

    def save(self):
        with open(self.config_file, 'w') as f:
            self.config.write(f)

    def reload(self):
        self.config.read([self.config_file])

    def _setup_config(self):
        self.general__ticket_limit = "3000"
        self.general__min_class_occur = "30"

        self.defaults__schedule = "0 0 * * *"

        self.svm__coefficient = "240.0"
        self.svm__cache_size = "2000"

        self.jira__default_resolutions = "Fixed"
        self.jira__default_statuses = "Resolved,Closed"

        self.auth__admin = hash_pwd("admin")

        self.save()

    def __getattr__(self, name):
        section_option = name.split("__", 1)
        if len(section_option) == 2 and section_option[0]:
            section, option = section_option

            if self.config.has_section(section) \
                    and self.config.has_option(section, option):
                return self.config.get(section, option)

        raise AttributeError("%s has no attribute '%s'"
                             % (self.__class__.__name__, name))

    def __setattr__(self, name, value):
        section_option = name.split("__", 1)
        if len(section_option) == 2 and section_option[0]:
            section, option = section_option

            if not self.config.has_section(section):
                self.config.add_section(section)

            if name != "auth__admin" or value:
                self.config.set(section, option, str(value))
        elif name in ['config_file', 'config']:
            super(Configuration, self).__setattr__(name, value)
        else:
            raise AttributeError("%s has no attribute '%s'"
                                 % (self.__class__.__name__, name))
Пример #15
0
def new(config, name, batch_size, epoch, learn, test, rate):
    """Prepare a job based on config file."""
    cfg = SafeConfigParser()
    cfg.read(config)

    check_paths(cfg.items('path'))

    jobname = make_unique(name or "mlmpr_caffe")
    current_run = 1

    if epoch and learn and test:
        update_iterations(cfg, int(batch_size), int(epoch), int(learn), int(test))

    if rate:
        cfg.set("caffe", "base_lr", (str(rate) + "\n"))

    cfg.add_section("status")
    cfg.set("status", "name", jobname)
    cfg.set("status", "current_run", str(current_run))

    prototxt = generate_prototxt(cfg, batch_size)
    cfg.set("status", "prototxt", prototxt)

    solver = generate_solver(cfg)
    cfg.set("status", "solver", solver)

    updater = generate_updater(cfg)
    cfg.set("status", "updater", updater)

    save_config(cfg)

    pbs = generate_pbs(cfg)

    submit(pbs)
Пример #16
0
class Config(object):
    """A ConfigParser wrapper to support defaults when calling instance
    methods, and also tied to a single section"""

    SECTION = 'deploy'

    def __init__(self, filename, extra_sources=()):


        self.cp = SafeConfigParser()
        self.cp.read(filename)
        if not self.cp.has_section(self.SECTION):
            self.cp.add_section(self.SECTION)
        self.cp.set(self.SECTION,"source_path",os.path.dirname(filename))


    def _getsources(self):
        sources = ['/etc/scrapyd/scrapyd.conf', r'c:\scrapyd\scrapyd.conf']
        sources += sorted(glob.glob('/etc/scrapyd/conf.d/*'))
        sources += ['scrapyd.conf']
        scrapy_cfg = closest_scrapy_cfg()
        if scrapy_cfg:
            sources.append(scrapy_cfg)
        return sources

    def _getany(self, method, option, default,section=None):
        if not section:
            section = self.SECTION
        try:
            return method(section, option)
        except (NoSectionError, NoOptionError):
            if default is not None:
                return default
            raise

    def get(self, option, default=None,section=None):
        return self._getany(self.cp.get, option, default,section)

    def getint(self, option, default=None,section=None):
        return self._getany(self.cp.getint, option, default)

    def getfloat(self, option, default=None,section=None):
        return self._getany(self.cp.getfloat, option, default,section)

    def getboolean(self, option, default=None,section=None):
        return self._getany(self.cp.getboolean, option, default,section)

    def items(self,  default=None,section=None):
        if not section:
            section =  self.SECTION
        try:
            return self.cp.items(section)
        except (NoSectionError, NoOptionError):
            if default is not None:
                return default
            raise
    def set(self,option,value,section=None):
        if not section:
            section = self.SECTION
        self.cp.set(section, option, value)
Пример #17
0
class Config(object):

    def __init__(self):
        self.config = SafeConfigParser()
        self.name = ''

    def parse(self, fname, override=()):
        logger.info('Reading configuration file: {}'.format(fname))
        if not os.path.isfile(fname):
            logger.interrupt('File doesn\'t exist: {}'.format(fname))
        self.config.optionxform = str
        self.config.read(fname)
        for section, option, value in override:
            if not self.config.has_section(section):
                self.config.add_section(section)
            self.config.set(section, option, value)

        basename = os.path.basename(fname)
        self.name = os.path.splitext(basename)[0]

    @safe
    def _get_options_as_dict(self, section):
        if section in self.config.sections():
            return {p: v for p, v in self.config.items(section)}
        else:
            return {}
Пример #18
0
 def _default(self):
     """
     write a default configuration file
     """
     path = conf_matrix.paths
     config_file = os.path.expanduser("~/.transiencerc")
     parser = SafeConfigParser()
     elements = [
         'recitations',
         'moods',
         'instructions',
         'durations',
         'glissandis',
         'interactions',
         'envelopes',
         'melos',
         'rhythms',
         #'poems',
         'etexts',
         ]
     for element in elements:
         parser.add_section(element)
         parser.set(element, 'sequence', "{}".format(path[random.randint(0,4)]))
     parser.add_section('midi')
     parser.set('midi', 'device', '-1')
     with open(config_file,"w") as f:
         parser.write(f)
Пример #19
0
    def __read_config(self):
        """ Read the object config file to control behavior

        This method will read the required configuration file which will set
        several options that control how the backup system operates. Many
        defaults are set based on our current SOP on database instance
        locations and setup.
        """

        conf_parse = SafeConfigParser()

        # Set all of our default parser options to honor the expected
        # behavior. This is not an exhaustive list of config entries.
        # Some are not listed as having no default.

        for section, options in self.pattern.iteritems():
            conf_parse.add_section(section)
            for option, value in options.iteritems():
                conf_parse.set(section, option, value)

        conf_parse.read(self.config_file)

        # Now that we've read the file, grab all items and turn them into
        # object attributes, prefixed with the containing section. This
        # makes it much easier to address each item.

        for k, v in self.pattern.items():
            sect = k.lower()
            cont = self.Container()

            for option in v:
                cont.__dict__[option] = conf_parse.get(k, option)

            self.__dict__[sect] = cont
Пример #20
0
 def on_makingof_config_file(self, filename):
     nunberofdatapersection = [0, len(p4R.s_radmax_1),
                               len(p4R.s_radmax_2),
                               len(p4R.s_radmax_3),
                               len(p4R.s_radmax_4),
                               len(p4R.s_radmax_5),
                               len(p4R.s_radmax_6),
                               len(p4R.s_radmax_7),
                               len(p4R.s_radmax_8)]
     pathini = [os.path.split(filename)[0]]*5
     data2ini = [p4R.version, p4R.last_modification] + pathini
     parser = SafeConfigParser()
     new_section_name = p4R.Radmax_all_section
     Initial_data = dict(zip(p4R.Radmax_all_section, data2ini))
     Initial_data.update(p4R.FitParamDefault)
     for i in range(len(p4R.Radmax_File_section)):
         parser.add_section(p4R.Radmax_File_section[i])
         k = nunberofdatapersection[i]
         r = nunberofdatapersection[i+1]
         new_section_name = new_section_name[k:]
         for l in range(r):
             parser.set(p4R.Radmax_File_section[i], new_section_name[l],
                        str(Initial_data[new_section_name[l]]))
     parser.write(open(filename, 'w'))
     a = ReadFile()
     a.on_read_init_parameters(os.path.join(p4R.current_dir, filename),
                               p4R.RadmaxFile)
Пример #21
0
    def run(self, args, config):
        unsuccessful = []
        for parcel in config.parcels:
            if not parcel.get('no-nose', False):
                nose_opts=parcel.get('nose', {})
                writer = SafeConfigParser()
                writer.add_section('nosetests')
                for key, value in nose_opts.iteritems():
                    if self.nose_has_option(key):
                        writer.set('nosetests', key, value)
                config_file = tempfile.NamedTemporaryFile(delete=False)
                try:
                    writer.write(config_file)
                finally:
                    config_file.close()

                    options = ['{BINDIR}/nosetests', '-c %s' % config_file.name]
                    options.extend(args.nose_arguments)
                try:
                    sh(' '.join(options), cwd=parcel['dir'])
                except SystemExit, e:
                    unsuccessful.append(parcel['name'])
                    notify('Continuing to next parcel')
                finally:
                    if args.keep_config_file:
Пример #22
0
def init_environment(args):
    """
    Initializes the environment.
    """    
    dirpath = dox_dir()
    
    cfg_path = os.path.join(dirpath,'dox.cfg')
    
    # Clean out previous config
    if os.path.exists(cfg_path):
        remove(cfg_path)
    
    # New Config File
    cfg = SafeConfigParser()
    cfg.add_section('Connection')
    cfg.set('Connection','endpoint',args.endpoint)
    cfg.set('Connection','library_key',args.library_key)
    cfg.set('Connection','project',args.project)
    cfg.set('Connection','content_type',args.content_type)
    cfg.set('Connection','body_field',args.body_field)
    if args.key_field:
        cfg.set('Connection','key_field',args.key_field)
    
    if args.api_key:
        cfg.set('Connection','api_key',args.api_key)
    
    with open(cfg_path,'wb') as cfg_file:
        cfg.write(cfg_file)
        
    # Make file hash directory
    hashdir_path = os.path.join(dirpath,'hashes')
    if not os.path.exists(hashdir_path):
        mkdir(hashdir_path)
Пример #23
0
def prepare_caching():
    ''' Value caching (used for coin and TB counts).'''
    cache = ConfigParser()
    try:
        cache.read('cache.dat')
        if not cache.has_section('TRAVELITEMS'):
            raise KeyError("TRAVELITEMS")
        if not cache.has_section('OWNCACHES'):
            raise KeyError("OWNCACHES")
    except KeyError as e:
        cache.add_section(e.args[0])
        print("No Travelbug/ Own Caches section found . A new one was "
              "generated.")
    except IOError:
        print("No cache file found . A new one was "
              "generated.")
    finally:
        try:
            with open('cache.dat', 'wb') as cachefile:
                cache.write(cachefile)
            cache.read('cache.dat')
        except IOError:
            print "Cachefile could not be written. Continuing without saving."
 
    return cache
Пример #24
0
class AppConfiguration(object):
    """
    Wrapper around SafeConfigParser to provide a nicer API
    """
    def __init__(self, verbosity=1, printer=None):
        self.parser = SafeConfigParser()
        self.printer = printer or Printer(verbosity)
        
    def __getitem__(self, item):
        """
        Get a section (Section instance) or create it if it doesn't exist.
        """
        if item not in self:
            self.parser.add_section(item)
        return Section(self.parser, item)
    
    def __contains__(self, item):
        """
        Check if this config has a section
        """
        return self.parser.has_section(item)
    
    def read_string(self, data):
        """
        Read the configuration from a string
        """
        sio = StringIO(data)
        sio.seek(0)
        self.parser.readfp(sio)
        
    def readfp(self, fp):
        self.parser.readfp(fp)
    
    def read(self, filepath):
        """
        Read the configuration from a filepath
        """
        self.parser.read(filepath)
    
    def write(self, filepath):
        """
        Write the configuration to a filepath
        """
        if not self.validate():
            return False
        with open(filepath, 'w') as fobj:
            self.parser.write(fobj)
        return True
    
    def write_file(self, fobj):
        if not self.validate():
            return False
        self.parser.write(fobj)
        return True
    
    def validate(self, validate_templates=True):
        """
        Validate this configuration
        """
        return validate_app(self, validate_templates, self.printer)
Пример #25
0
def patch(overrides):
    """
    Perform a mock.patch on the server config that changes only the values passed in the overrides
    argument.

    :param overrides: A dictionary specifying the config overrides to apply. The keys should be
                      config sections, and each section should be a dictionary of setting and value
                      pairs.
    :type  overrides: dict
    """
    new_config = SafeConfigParser()

    # Copy the old config to the new config. deepcopy() complained about being asked to do this,
    # which is why it is done in this manual fashion.
    for section in config.sections():
        new_config.add_section(section)
        for key, value in config.items(section):
            new_config.set(section, key, value)

    # Overlay the overrides onto our new copy of the config
    for section, settings in overrides.items():
        for key, value in settings.items():
            new_config.set(section, key, value)

    # Returning the patch this way allows us to emulate all the normal mock.patch abilities, such as
    # acting as a function or class decorator, as well as acting as a context manager.
    return mock.patch('pulp.server.config.config', new_config)
Пример #26
0
    def create_header(self, data_only):
        '''
        Create the backup file header that contains the meta data about
        this particular backup.
        '''
        config = SafeConfigParser()
        config.add_section("ipa")
        if data_only:
            config.set('ipa', 'type', 'DATA')
        else:
            config.set('ipa', 'type', 'FULL')
        config.set('ipa', 'time', time.strftime(ISO8601_DATETIME_FMT, time.gmtime()))
        config.set('ipa', 'host', api.env.host)
        config.set('ipa', 'ipa_version', str(version.VERSION))
        config.set('ipa', 'version', '1')

        dn = DN(('cn', api.env.host), ('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn)
        services_cns = []
        try:
            conn = self.get_connection()
            services = conn.get_entries(dn, conn.SCOPE_ONELEVEL)
        except errors.NetworkError:
            self.log.critical(
              "Unable to obtain list of master services, continuing anyway")
        except Exception as e:
            self.log.error("Failed to read services from '%s': %s" %
                (conn.host, e))
        else:
            services_cns = [s.single_value['cn'] for s in services]

        config.set('ipa', 'services', ','.join(services_cns))
        with open(self.header, 'w') as fd:
            config.write(fd)
Пример #27
0
    def mock_config(self):
        self.old_config = checkin.CONFIG
        
        defaults = {'spacewalk': {'host': 'spacewalkhost',
                                  'ssh_key_path': 'spacwealk_ssh_key_path'},
                    'main': {'socket_timeout': '300', 'num_threads': '4'},
                    'splice': {'hostname': 'test_hostname',
                               'port': '8888',
                               'handler': 'test_handler',
                               'splice_id_cert': 'test_cert',
                               'splice_id_key': 'test_key',
                               'splice_ca_cert': 'test_ca',
                               'splice_server_environment': 'test_sse',
                               'splice_server_hostname': 'test_ssh',
                               'splice_server_description': 'test_ssd',}
                   }

        config = SafeConfigParser(defaults)

        for section, configs in defaults.items():
            if not config.has_section(section):
                config.add_section(section)
            for key, value in configs.items():
                config.set(section, key, value)

        checkin.CONFIG = config

        return config
Пример #28
0
def SaveToConfig(section=None, variable=None, value=None):
    """
    Add a variable and value to section in the config file.
    
    Keyword arguments:
    section -- Section to with the variable - value pair will be added
    variable -- Option that will be added to the config file
    value -- Value of the variable that will be added
    """

    cfg = SafeConfigParser()
    try:
        with codecs.open(autosub.CONFIGFILE, 'r', autosub.SYSENCODING) as f:
            cfg.readfp(f)
    except:
        #no config yet
        pass

    if cfg.has_section(section):
        cfg.set(section, variable.encode('utf8'), value.encode('utf8'))
        edited = True
    else:
        cfg.add_section(section)
        cfg.set(section, variable.encode('utf8'), value.encode('utf8'))
        edited = True

    if edited:
        with open(autosub.CONFIGFILE, 'wb') as file:
            cfg.write(file)
Пример #29
0
def generate_config_parser(config, include_all=False):
    """
    Generates a config parser from a configuration dictionary.

    The dictionary contains the merged informations of the schema and,
    optionally, of a source configuration file. Values of the source
    configuration file will be stored in the *value* field of an option.
    """

    # The allow_no_value allows us to output commented lines.
    config_parser = SafeConfigParser(allow_no_value=True)
    for section_name, option_name in _get_included_schema_sections_options(config, include_all):

        if not config_parser.has_section(section_name):
            config_parser.add_section(section_name)

        option = config[section_name][option_name]

        if option.get('required'):
            config_parser.set(section_name, '# REQUIRED')

        config_parser.set(section_name, '# ' + option.get('description', 'No description provided.'))

        if option.get('deprecated'):
            config_parser.set(section_name, '# DEPRECATED')

        option_value = _get_value(option)
        config_parser.set(section_name, option_name, option_value)

        config_parser.set(section_name, '')

    return config_parser
Пример #30
0
def GetScreenshotOptions(configfile):
   log = logging.getLogger('')
   opts = ScreenshotOptions()

   # Load config
   config = SafeConfigParser()
   config.add_section('screenshot')
   config.set('screenshot', 'HOME', os.environ['HOME'])

   # Load default config
   config.readfp(StringIO(DEFAULT_CONFIG))

   # if command line given
   cfiles = []
   if configfile:
      cfiles = config.read( [ configfile ] )
      log.info("Loaded configuration %s" % (", ".join(cfiles)))

   if len(cfiles) == 0:
      # load user config from $HOME/.screenshot/screenshot.ini
      conffile = os.path.join(os.environ['HOME'], ".screenshot/screenshot.ini")
      if os.path.exists(conffile):
         cfiles = config.read([conffile])
         log.info("Loaded configuration %s" % (", ".join(cfiles)))
      else:
         log.warn("No configuration loaded, using defaults")

   opts.load_options(config)

   return opts
Пример #31
0
def _modify_config_profile(config_file, profile):
    config = SafeConfigParser()
    config.read(config_file)

    if not config.has_section(profile):
        config.add_section(profile)

    config = _set_attribute_of_profile(config, profile, 'gstack_bind_address',
                                       'gstack bind address', 'localhost')
    config = _set_attribute_of_profile(config, profile, 'gstack_port',
                                       'gstack bind port', '5000')
    config = _set_attribute_of_profile(config, profile, 'cloudstack_host',
                                       'Cloudstack host', 'localhost')
    config = _set_attribute_of_profile(config, profile, 'cloudstack_port',
                                       'Cloudstack port', '8080')
    config = _set_attribute_of_profile(config, profile, 'cloudstack_protocol',
                                       'Cloudstack protocol', 'http')
    config = _set_attribute_of_profile(config, profile, 'cloudstack_path',
                                       'Cloudstack path', '/client/api')

    return config
Пример #32
0
def dumpIniSections(iniFile, iniSections):
    """
    convert iniSections object, expected to be a hash or hashes, into an iniFile
    """
    from ConfigParser import SafeConfigParser

    config = SafeConfigParser()
    config.optionxform = str

    def clean_value(v):
        if v is None: return ""
        else: return str(v)

    for section in iniSections.keys():
        config.add_section(section)
        for k, v in iniSections[section].items():
            config.set(section, k, clean_value(v))

    configfp = open(iniFile, "w")
    config.write(configfp)
    configfp.close()
Пример #33
0
def write_config_field(config_path, section_name, field_name, field_value):
    """
    Set a particular config file field
    Return True on success
    Return False on error
    """
    if not os.path.exists(config_path):
        return False

    parser = SafeConfigParser()
    parser.read(config_path)

    if not parser.has_section(section_name):
        parser.add_section(section_name)
        
    parser.set(section_name, field_name, '{}'.format(field_value))
    with open(config_path, 'w') as fout:
        os.fchmod(fout.fileno(), 0600)
        parser.write(fout)

    return True
def store_token(token):
    """
    Stores a token string in the config file
    :param token: token string to store
    :return:
    """
    config = SafeConfigParser()
    config.read(consts.CONFIG_FILE)
    sections = config.sections()
    if consts.SECRETS_SECTION not in sections:
        config.add_section(consts.SECRETS_SECTION)
    config.set(consts.SECRETS_SECTION, consts.USER_TOKEN_LL, token)

    try:
        with open(consts.CONFIG_FILE, 'w') as f:
            config.write(f)
    # TODO: work out permission issues
    except Exception as e:
        print ("ERROR: Error writing token to config file {}. "
               "{}".format(consts.CONFIG_FILE, e))
        exit(1)
Пример #35
0
    def save(self):
        """
        Save environment settings into environment directory
        """
        cp = SafeConfigParser()

        cp.add_section('datacats')
        cp.set('datacats', 'name', self.name)
        cp.set('datacats', 'ckan_version', self.ckan_version)
        cp.set('datacats', 'port', str(self.port))

        if self.deploy_target:
            cp.add_section('deploy')
            cp.set('deploy', 'target', self.deploy_target)

        if self.site_url or self.always_prod:
            if self.site_url:
                cp.set('datacats', 'site_url', self.site_url)
            if self.always_prod:
                cp.set('datacats', 'always_prod', 'true')

        with open(self.target + '/.datacats-environment', 'w') as config:
            cp.write(config)

        # save passwords to datadir
        cp = SafeConfigParser()

        cp.add_section('passwords')
        for n in sorted(self.passwords):
            cp.set('passwords', n.lower(), self.passwords[n])

        with open(self.datadir + '/passwords.ini', 'w') as config:
            cp.write(config)

        self._update_saved_project_dir()
Пример #36
0
def get_config():
    """Return the ConfigParser object with defaults set."""
    configparser = SafeConfigParser({
        'default_user': getenv(
            'DEFAULT_USER',
            'default_user'
        )
    })
    configparser.add_section('celery')
    configparser.set('celery', 'broker_url', getenv(
        'BROKER_URL', 'pyamqp://'))
    configparser.set('celery', 'backend_url', getenv(
        'BACKEND_URL', 'rpc://'))
    configparser.add_section('notifications')
    configparser.set('notifications', 'policy_url', getenv(
        'POLICY_URL', 'http://127.0.0.1:8181'))
    configparser.add_section('database')
    configparser.set('database', 'peewee_url', getenv(
        'PEEWEE_URL', 'sqliteext:///db.sqlite3'))
    configparser.set('database', 'connect_attempts', getenv(
        'DATABASE_CONNECT_ATTEMPTS', '10'))
    configparser.set('database', 'connect_wait', getenv(
        'DATABASE_CONNECT_WAIT', '20'))
    configparser.read(CONFIG_FILE)
    return configparser
Пример #37
0
def configure(filename=None):
    """This function gives to the user application a chance to define where
    configuration file should live. Subsequent calls to this function will have
    no effect, unless you call :func:`reconfigure`.

    :param str filename: Full path to configuration file.

    """
    global retry

    if getattr(configure, '_configured', False):
        return

    filename = filename or DEFAULT_CONFIG_FILENAME
    _ensure_directory(filename)

    parser = SafeConfigParser()

    if os.path.isfile(filename):
        with open(filename, 'r') as fp:
            parser.readfp(fp)

    if not parser.has_section(RETRY_SECTION):
        parser.add_section(RETRY_SECTION)
        parser.set(RETRY_SECTION, 'max_tries',
                   str(constants.BACKOFF_DEFAULT_MAXTRIES))
        parser.set(RETRY_SECTION, 'delay',
                   str(constants.BACKOFF_DEFAULT_DELAY))
        parser.set(RETRY_SECTION, 'factor',
                   str(constants.BACKOFF_DEFAULT_FACTOR))

        with open(filename, 'wb') as fp:
            parser.write(fp)

    retry = RetrySettings(max_tries=parser.getint(RETRY_SECTION, 'max_tries'),
                          delay=parser.getint(RETRY_SECTION, 'delay'),
                          factor=parser.getint(RETRY_SECTION, 'factor'))

    setattr(configure, '_configured', True)
    setattr(configure, '_configured_filename', filename)
class Config:
    def __init__(self, config_name):
        self.config_name = config_name
        self.parser = SafeConfigParser()
        self.config = {}
        self.section = 'progress'

    def exists(self):
        return os.path.isfile(self.config_name)

    def delete(self):
        try:
            os.remove(config_file_name)
        except OSError:
            pass

    def set(self, key, value):
        if not self.exists():
            self.parser.add_section(self.section)
            config_file = open(self.config_name, 'w+')
            self.parser.write(config_file)
            config_file.close()

        with open(self.config_name, 'w') as config_file:
            self.config[key] = value == 'True'
            self.parser.set('progress', str(key), str(value))
            self.parser.write(config_file)

    def get(self, key, type='bool', default=False):
        if type == 'bool':
            try:
                self.parser.read(self.config_name)
                val = self.parser.get(self.section, key) == 'True'
            except:
                self.set(key, str(default))
                return
        else:
            raise TypeError

        self.config[key] = val
Пример #39
0
def write_config_file(opts, config_file):
    """
    Write our config file with the given options dict.
    Each key is a section name, and each value is the list of options.

    If the file exists, do not remove unaffected sections.  Instead,
    merge the sections in opts into the file.

    Return True on success
    Raise on error
    """

    if 'ysi-client' in opts:
        opts['ysi-client'] = clear_runtime_fields(opts['ysi-client'])

    opts = clear_runtime_fields(opts)

    parser = SafeConfigParser()

    if os.path.exists(config_file):
        parser.read(config_file)

    for sec_name in opts:
        sec_opts = opts[sec_name]

        if parser.has_section(sec_name):
            parser.remove_section(sec_name)

        parser.add_section(sec_name)
        for opt_name, opt_value in sec_opts.items():
            if opt_value is None:
                opt_value = ''

            parser.set(sec_name, opt_name, '{}'.format(opt_value))

    with open(config_file, 'w') as fout:
        os.fchmod(fout.fileno(), 0600)
        parser.write(fout)

    return True
Пример #40
0
def generate():
    """
    Generates an example configuration file.
    """
    parser = SafeConfigParser()
    parser.add_section('main')
    parser.set('main', 'apikey', 'your api key')

    foosection_1 = "project.foo_app_1"
    parser.add_section(foosection_1)
    parser.set(foosection_1, 'project_id', 'your project id')
    parser.set(foosection_1, 'type', 'apple_strings')
    parser.set(foosection_1, 'terms',
               'foo_app_1/Localizations/en.lproj/Localizable.strings')
    parser.set(foosection_1, 'trans.en',
               'foo_app_1/Localizations/en.lproj/Localizable.strings')
    parser.set(foosection_1, 'trans.nl',
               'foo_app_1/Localizations/nl.lproj/Localizable.strings')
    parser.set(foosection_1, 'trans.fr',
               'foo_app_1/Localizations/fr.lproj/Localizable.strings')

    foosection_2 = "project.foo_app_2"
    parser.add_section(foosection_2)
    parser.set(foosection_2, 'project_id', 'your project id')
    parser.set(foosection_2, 'type', 'apple_strings')
    parser.set(foosection_2, 'trans.pl',
               'foo_app_2/Localizations/pl.lproj/Localizable.strings')

    parser.write(open(FILENAME, "w+"))
Пример #41
0
def configuration_write():
    global APP_API

    global APP_CFG_TWITTER_NICK
    global APP_CFG_TWITTER_ARCHIVE
    global APP_CFG_CONSUMER_KEY
    global APP_CFG_CONSUMER_SECRET
    global APP_CFG_ACCESS_TOKEN_KEY
    global APP_CFG_ACCESS_TOKEN_SECRET

    global APP_DFT_TWITTER_NICK
    global APP_DFT_TWITTER_ARCHIVE
    global APP_DFT_CONSUMER_KEY
    global APP_DFT_CONSUMER_SECRET
    global APP_DFT_ACCESS_TOKEN_KEY
    global APP_DFT_ACCESS_TOKEN_SECRET

    # WRITE FILE
    CONFIG_FILE_PATH = APP_PATH + '/' + APP_CONFIG_FILE

    config_file = SafeConfigParser()
    config_file.read(CONFIG_FILE_PATH)
    # STORE account
    config_file.add_section('account')
    config_file.set('account', 'nick', APP_CFG_TWITTER_NICK)
    config_file.set('account', 'archive_file', APP_CFG_TWITTER_ARCHIVE)
    # AUTH account
    config_file.add_section('authorization')
    config_file.set('authorization', 'consumer_key', APP_CFG_CONSUMER_KEY)
    config_file.set('authorization', 'consumer_secret',
                    APP_CFG_CONSUMER_SECRET)
    config_file.set('authorization', 'access_token_key',
                    APP_CFG_ACCESS_TOKEN_KEY)
    config_file.set('authorization', 'access_token_secret',
                    APP_CFG_ACCESS_TOKEN_SECRET)

    print "CONFIG WRITE: Writing config %s ..." % CONFIG_FILE_PATH
    with open(CONFIG_FILE_PATH, 'w') as file_to_write:
        config_file.write(file_to_write)
    print "CONFIG WRITE: Writing succeeded." % CONFIG_FILE_PATH
Пример #42
0
def get_config():
    """Return the ConfigParser object with defaults set."""
    configparser = SafeConfigParser(
        {'default_user': getenv('DEFAULT_USER', 'default_user')})
    configparser.add_section('celery')
    configparser.set('celery', 'broker_url',
                     getenv('BROKER_URL', 'redis://*****:*****@localhost/pacifica_notifications'
        ))
    configparser.set('database', 'connect_attempts',
                     getenv('DATABASE_CONNECT_ATTEMPTS', '10'))
    configparser.set('database', 'connect_wait',
                     getenv('DATABASE_CONNECT_WAIT', '20'))
    configparser.read(CONFIG_FILE)
    return configparser
Пример #43
0
    def __init__(self, config_file='config.cfg'):
        super(Elastic, self).__init__()

        self.percentage = 10.0
        self.minimum_occurrences = 250

        # The ConfigParser documentation points out that there's no way to force defaults config option
        # outside the "DEFAULT" section.
        config = ConfigParser()
        config.read(config_file)
        if not config.has_section('elastic'):
            config.add_section('elastic')

        for option, value in {
                'use_ssl': 'True',
                'host': '127.0.0.1',
                'version': '2',
                'index': 'nxapi',
                'doc_type': 'events'
        }.items():
            if not config.has_option('elastic', option):
                config.set('elastic', option, value)

        self.version = config.getint('elastic', 'version')
        self.index = config.get('elastic', 'index')
        use_ssl = config.getboolean('elastic', 'use_ssl')
        host = config.get('elastic', 'host')
        self.doc_type = config.get('elastic', 'doc_type')
        self.client = connections.create_connection(hosts=[host],
                                                    use_ssl=use_ssl,
                                                    index=self.index,
                                                    version=self.version,
                                                    doc_type=self.doc_type,
                                                    timeout=30,
                                                    retry_on_timeout=True)

        Event.init(index=self.index)
        index = Index(self.index, using=self.client)
        index.doc_type(Event)
        self.initialize_search()
Пример #44
0
class prefs:
    def __init__(self):
        self.filename = 'formPref.ini'
        self.config = SafeConfigParser()
        self.config.read(self.filename)
        if len(self.config.sections()) == 0:
            self.defaults()

    def defaults(self):
        self.config.add_section('general')
        self.config.set('general', 'filename', '')
        self.config.set('general', 'filepath', os.getcwd())
        self.config.set('general', 'recfile', '')
        self.config.set('general', 'recpath', os.getcwd())
        self.config.set('general', 'level', '0.5')
        self.config.set('general', 'criterion', '30')
        self.config.set('general', 'conditions', 'left,right')
        self.config.set('general', 'history', '1000')
        self.write()

    def set(self, what, varstr):
        self.config.set('general', what, varstr)
        self.write()

    def get(self, what):
        return self.config.get('general', what)

    def getConditionsStr(self):
        return self.config.get('general', 'conditions')

    def getConditions(self):
        return self.config.get('general', 'conditions').split(',')

    def setConditions(self, conditions):
        self.config.set('general', 'conditions', conditions)
        self.write()

    def write(self):
        with open(self.filename, 'w') as f:
            self.config.write(f)
Пример #45
0
def main(argv):
    config = SafeConfigParser()
    config.read(SYSTEM_BOTO_CONFIG_TEMPLATE)

    # TODO(jbeda): Figure out if we need a retry here.
    project_id = GetNumericProjectId()
    if not project_id:
        # Our project doesn't support service accounts.
        return

    if not config.has_section('GSUtil'):
        config.add_section('GSUtil')
    config.set('GSUtil', 'default_project_id', project_id)
    config.set('GSUtil', 'default_api_version', '2')

    if not config.has_section('GoogleCompute'):
        config.add_section('GoogleCompute')
    # TODO(jbeda): Plumb a metadata value to set this.  We probably want
    # to namespace the metadata values in some way like
    # 'boto_auth.servicee_account'.
    config.set('GoogleCompute', 'service_account', 'default')

    if not config.has_section('Plugin'):
        config.add_section('Plugin')
    config.set('Plugin', 'plugin_directory', AUTH_PLUGIN_DIR)

    with open(SYSTEM_BOTO_CONFIG, 'w') as configfile:
        AddConfigFileHeader(configfile)
        config.write(configfile)
Пример #46
0
class Propiedades:
    # variables de clase
    ficheroIni = "config.ini"
    bApt = False
    bGit = False
    bDocker = False

    def __init__(self):
        self.seccion = "Config"
        self.check_config_file()

    # Verifica si existe el fichero de configuración y si no existe lo crea
    def check_config_file(self):
        directory = os.getenv("HOME") + '/.config/indicador-proxy'
        if not os.path.exists(directory):
            os.makedirs(directory)
        self.config_file = directory + '/' + self.ficheroIni
        if (not os.path.exists(self.config_file)):
            self.config = SafeConfigParser()
            self.config.read(self.config_file)
            self.config.add_section(self.seccion)
            self.config.set(self.seccion, "proxy_apt", "False")
            self.config.set(self.seccion, "proxy_git", "False")
            self.config.set(self.seccion, "proxy_docker", "False")
            with open(self.config_file, 'wb') as configfile:
                self.config.write(configfile)

    def lee(self, clave):
        self.config = SafeConfigParser()
        self.config.read(self.config_file)
        try:
            return self.config.get(self.seccion, clave)
        except:
            pass

    def escribe(self, clave, valor):
        self.config.set(self.seccion, clave, str(valor))
        with open(self.config_file, 'wb') as configfile:
            self.config.write(configfile)
Пример #47
0
def load_configuration(config_filenames):
    """
    Load a configuration object from the default values and the provided files.
    The default values are applied first and are overridden by a value in any
    of the files provided.

    :param config_filenames: A list of files containing config values for the streamer.
                             These should be readable by the user running the streamer.
    :type  config_filenames: list of str

    :return: A configuration for the Pulp streamer which is guaranteed to have a value
             for every configuration option.
    :rtype:  SafeConfigParser
    """
    config = SafeConfigParser()
    for section, settings in DEFAULT_VALUES.items():
        config.add_section(section)
        for option, value in settings.items():
            config.set(section, option, value)
    config.read(config_filenames)

    return config
Пример #48
0
    def setserver(self):
        '''Set server for the client to manage (currently local or gcloud) and creates Loom settings directory.'''
        server_location_file = os.path.expanduser(SERVER_LOCATION_FILE)
        # Create directory/directories if they don't exist
        ini_dir = os.path.dirname(server_location_file)
        if not os.path.exists(ini_dir):
            print 'Creating Loom settings directory %s...' % ini_dir
            os.makedirs(ini_dir)

        # Write server.ini file
        config = SafeConfigParser()
        config.add_section('server')
        config.set('server', 'type', self.args.type)
        if self.args.type == 'gcloud':
            name = self.args.name
            config.set('server', 'name', name)
        with open(server_location_file, 'w') as configfile:
            print 'Updating %s...' % server_location_file
            config.write(configfile)

        # Copy NGINX config file to same place
        shutil.copy(NGINX_CONFIG_FILE, ini_dir)
Пример #49
0
def _modify_config_profile(config_file, profile, advanced_network_enabled):
    """
    Modify configuration profile.

    @param config_file: current config file configuration.
    @param profile: the profile to set the attribute in.
    @return: configparser configuration.
    """
    config = SafeConfigParser()
    config.read(config_file)

    if not config.has_section(profile):
        config.add_section(profile)

    config = _set_mandatory_attributes_of_profile(config, profile)

    if advanced_network_enabled:
        config = _set_advanced_network_attributes_of_profile(config, profile)

    config = _set_optional_attributes_of_profile(config, profile)

    return config
Пример #50
0
def load_config():

    global __dir__
    cfg_folder = __dir__ + '/config.ini'
    cfg_dict = {
        'ce_ip': '127.0.0.1',
        'ce_port': '8000',
        'sched_ip': '0.0.0.0',
        'sched_port': '88'
    }
    cfg = SafeConfigParser({'ALL': '0.0.0.0'})
    cfg.read(cfg_folder)

    if not os.path.isfile(cfg_folder):
        cfg.add_section('CONFIG')
        for k, v in cfg_dict.iteritems():
            cfg.set('CONFIG', k, v)
        cfg.write(open(cfg_folder, 'w'))
    else:
        cfg_dict.update(dict(cfg.items('CONFIG')))

    return cfg_dict
Пример #51
0
    def csw(self, *args, **kwargs):
        """Wrapper around pycsw for dispatching CSW requests"""        
        
        # Cycle through the CONFIGURATION dictionary and push the params into the config object
        config = SafeConfigParser()
        for section, options in CONFIGURATION.iteritems():
            config.add_section(section)
            for k, v in options.iteritems():
                config.set(section, k, v)
    
        # Calculate and insert the server URL into the config
        server_url = 'http://%s%s' % \
            (kwargs["environ"]['HTTP_HOST'],
             kwargs["environ"]['PATH_INFO'])    
        config.set('server', 'url', server_url)

        # Make a copy of the WSGI request environment and add parameters
        env = kwargs["environ"].copy()
                
        query = kwargs["environ"]["QUERY_STRING"]
        if query != "":
            absolute_uri = "%s?%s" % (server_url, query)
        else:
            absolute_uri = server_url
            
        env.update({ 
            'local.app_root': os.path.dirname(__file__),                
            'REQUEST_URI': absolute_uri
        })
        
        # Create an instance of pycsw's CSW class to handle the request 
        csw = server.Csw(config, env)
    
        # Run the request
        content = csw.dispatch_wsgi()
        
        # Set the response Content-type, and return the result
        kwargs["pylons"].response.content_type = csw.contenttype       
        return content
Пример #52
0
def save_rose_username(username):
    """
    Add the Rose username & server settings to Subversion's config file
    """
    # Run 'svn help' to create the config files if they don't exist
    svn = Popen(['svn', 'help'], stdout=PIPE)
    svn.communicate()

    config = SafeConfigParser()
    config.read(svn_servers)

    if not config.has_section('groups'):
        config.add_section('groups')
    config.set('groups', 'metofficesharedrepos', 'code*.metoffice.gov.uk')

    if not config.has_section('metofficesharedrepos'):
        config.add_section('metofficesharedrepos')
    config.set('metofficesharedrepos', 'username', username)
    config.set('metofficesharedrepos', 'store-plaintext-passwords', 'no')

    with open(svn_servers, 'w') as f:
        config.write(f)
Пример #53
0
def set_to_config(option, value, section=None, path=conf_path):
    cnf = SafeConfigParser()
    try:
        if not section:
            section = conf_contents.get('section')
        cnf.readfp(open(path, 'r'))
        if not cnf.has_section(section) and section.lower() != 'default':
            cnf.add_section(section)
        cnf.set(section, option, value)
        with open(path, 'w') as f:
            cnf.write(f)
        return True
    except IOError:
        print "Error reading/writing {}".format(path)
    except KeyError:
        print "Section: {} not found!".format(section)
    except ValueError as e:
        print e
    except NoSectionError:
        print "Section: {} not found!".format(section)
    except NoOptionError:
        print "Option: {} not found!".format(option)
Пример #54
0
    def _load_configuration(cls, config_file=None):
        """Check the configuration files and load the global 'config' object from them."""
        config = SafeConfigParser()
        # add the defaults first
        for section, settings in CmdContext.DefaultValues.items():
            config.add_section(section)
            for option, value in settings.items():
                config.set(section, option, value)
                # read the config files

        config_files = []
        if config_file:
            config_files.append(config_file)
        else:
            config_files.extend(CmdContext.DefaultConfigFiles)

        for config_file in config_files:
            if os.access(config_file, os.F_OK | os.R_OK):
                config.read(config_file)
                return config

        return config
Пример #55
0
def new(config, name):
    """Prepare a job based on config file."""
    cfg = SafeConfigParser()
    cfg.read(config)

    check_paths(cfg.items('path'))

    jobname = make_unique(name or "mlmpr_caffe")
    current_run = 1

    cfg.add_section("status")
    cfg.set("status", "name", jobname)
    cfg.set("status", "current_run", str(current_run))

    solver = generate_solver(cfg)
    cfg.set("status", "solver", solver)

    save_config(cfg)

    pbs = generate_pbs(cfg)

    submit(pbs)
Пример #56
0
def write_config_file(opts, config_file):
    """
    Write our config file with the given options dict.
    Each key is a section name, and each value is the list of options.

    Return True on success
    Raise on error
    """

    if 'blockstack-client' in opts:
        assert 'path' not in opts['blockstack-client']
        assert 'dir' not in opts['blockstack-client']

    assert 'path' not in opts
    assert 'dir' not in opts

    parser = SafeConfigParser()

    if os.path.exists(config_file):
        parser.read(config_file)

    for sec_name in opts:
        sec_opts = opts[sec_name]

        if parser.has_section(sec_name):
            parser.remove_section(sec_name)

        parser.add_section(sec_name)
        for opt_name, opt_value in sec_opts.items():
            if opt_value is None:
                opt_value = ''

            parser.set(sec_name, opt_name, '{}'.format(opt_value))

    with open(config_file, 'w') as fout:
        os.fchmod(fout.fileno(), 0600)
        parser.write(fout)

    return True
Пример #57
0
 def saveSettings(self):
     saveFileName = str(
         QtGui.QFileDialog.getSaveFileName(
             self,
             'Save Settings',
             '',
             filter="Settings files (*.cfg);;",
             selectedFilter="Settings files (*.cfg)"))
     filename, file_extension = os.path.splitext(saveFileName)
     config = SafeConfigParser()
     for name in self.strip.records:
         # print name,' record = ', self.strip.records[name]
         section = str(name)
         config.add_section(section)
         config.set(section, 'name', str(self.strip.records[name]['name']))
         print 'name = ', self.strip.records[name]['name']
         print 'pen = ', self.strip.records[name]['pen']
         try:
             config.set(section, 'pen',
                        str(self.strip.records[name]['pen'].name()))
         except:
             config.set(section, 'pen',
                        str(self.strip.records[name]['pen']))
         config.set(section, 'freq',
                    str(1.0 / self.strip.records[name]['timer']))
         config.set(section, 'maxlength',
                    str(self.strip.records[name]['maxlength']))
         config.set(section, 'functionForm',
                    str(self.strip.records[name]['functionForm']))
         config.set(section, 'functionArgument',
                    str(self.strip.records[name]['functionArgument']))
         config.set(section, 'arg', str(self.strip.records[name]['arg']))
         config.set(section, 'logScale',
                    str(self.strip.records[name]['logScale']))
         config.set(section, 'verticalRange',
                    str(self.strip.records[name]['verticalRange']))
     with open(saveFileName, 'wb') as configfile:
         config.write(configfile)
Пример #58
0
def postTweet(tweetText):

    # Open the config file
    config = SafeConfigParser()
    config.read('config.ini')

    # Try to get the consumer keys. If we can't, add blank entries to the config
    try:
        consumerKey = config.get('auth', 'consumerKey')
        consumerSecret = config.get('auth', 'consumerSecret')
    except:
        print "Error! config.ini must contain the consumer key and consumer secret."
        config.add_section('auth')
        config.set('auth', 'consumerKey', '')
        config.set('auth', 'consumerSecret', '')
        with open('config.ini', 'w') as f:
            config.write(f)

    # Now try to get the access keys. If we can't, try to get them.
    try:
        acessKey = config.get('auth', 'accessKey')
        accessSecret = config.get('auth', 'accessSecret')
    except:
        getAccessTokens()
        config.read('config.ini')
        acessKey = config.get('auth', 'accessKey')
        accessSecret = config.get('auth', 'accessSecret')

    # Connect to the Twitter API
    auth = tweepy.OAuthHandler(consumerKey, consumerSecret)
    auth.set_access_token(acessKey, accessSecret)
    api = tweepy.API(auth)

    # Post the Tweet
    try:
        api.update_status(tweetText)
    except tweepy.TweepError:
        print 'Error! Failed to post status update.'
Пример #59
0
def test_create_and_setup(tmpdir):
    directory = str(tmpdir.realpath())
    ipc_server = CollectServer()
    ipc_chatter = QueueReceiver()
    app = RecorderApplication(config_dir=directory)
    app.publisher = CollectPublisher()
    app.camera = QueueCamera()
    app.ipc_server = ipc_server
    app.pilot = lambda: None
    app.vehicle = lambda: None
    app.ipc_chatter = lambda: ipc_chatter.pop_latest()

    try:
        # The default settings must result in a workable instance.
        app.setup()
        assert len(ipc_server.collect()) == 1
        assert not bool(ipc_server.get_latest())
        assert app.get_process_frequency() != 0

        #
        # Change the configuration and request a restart.
        # Write a new config file.
        previous_process_frequency = app.get_process_frequency()
        new_process_frequency = previous_process_frequency + 10
        _parser = SafeConfigParser()
        _parser.add_section('recorder')
        _parser.set('recorder', 'clock.hz', str(new_process_frequency))
        with open(os.path.join(directory, 'test_config.ini'), 'wb') as f:
            _parser.write(f)
        #
        # Issue the restart request.
        ipc_chatter.add(dict(command='restart'))
        app.step()
        assert len(ipc_server.collect()) == 2
        assert not bool(ipc_server.get_latest())
        assert app.get_process_frequency() == new_process_frequency
    finally:
        app.finish()
Пример #60
0
def main():
    if len(sys.argv) < 3:
        sys.exit(
            'Usage: AddUser.py <username> <password> \n Set password to "-" to delete a user'
        )

    parser = SafeConfigParser()
    parser.read('users.ini')

    if not parser.has_section('users'):
        parser.add_section('users')

    try:
        if (sys.argv[2] == "-"):
            parser.remove_option('users', sys.argv[1])
        else:
            parser.set('users', sys.argv[1],
                       hashlib.md5(sys.argv[2].strip()).hexdigest())
    except:
        pass

    # prevent an empty file -- always have a default user if there is no other user
    if len(parser.options('users')) == 0:
        parser.set('users', 'default', hashlib.md5('default').hexdigest())

    file = open('users.ini', 'w')
    file.write(
        '#This is the list of users/encrypted passwords for the Linux CNC Web Server\n\n'
    )
    file.write('#Use the included python script AddUser to add users\n')
    file.write(
        '#Users can be removed by deleting the entries in this file with their user name\n'
    )
    file.write(
        '#This file will be auto-generated and overwritten by the AddUser program\n\n'
    )
    parser.write(file)
    file.close()