def hour_set(arg, hour):
     cp = ConfigParser()
     cp.read("conf.txt")
     cp.set("pills_must_be_taken", "hour", hour)
     hd = open("conf.txt", "w")
     cp.write(hd)
     hd.close()
Example #2
0
def auth_springpad_client(config_file=None):
    """
    Auth the application to make to be allowed to access to user's springpad
    account. If not a valid config file is provided it will prompt the user to
    visit an url in order to allow the application to access to its account
    and it will store authentication details in `config_file`.
    args:
        config_file: the configuration file path to be used. If it is not
            provided, '~/.springpad' will be used instead.
    returns: SpringpadClient instance to interact with the authenticated
        account.
    """
    config_file = config_file or os.path.expanduser("~/.springpad")
    config = ConfigParser()
    config.read([config_file])
    token = config.get("access", "token") if config.has_option("access", "token") else None
    if token:
        token = oauth.OAuthToken.from_string(token)

    client = SpringpadClient(SPRINGPAD_CONSUMER_KEY, SPRINGPAD_CONSUMER_PRIVATE, token)

    if not client.access_token:
        req_token = client.get_request_token()
        print "Please grant access to your springpad account in the following url:\n"
        print "http://springpad.com/api/oauth-authorize?{0}\n".format(req_token)
        print "Once authorized, press intro to continue:",
        raw_input()
        client.access_token = client.get_access_token(req_token)
        config.add_section("access")
        config.set("access", "token", str(client.access_token))
        with open(os.path.expanduser(config_file), "w") as cf:
            config.write(cf)
    return client
Example #3
0
class UserConfig:

    def __init__(self, filename=default_user_config_file):
        self.parser = ConfigParser()
        self.parser.read(filename)
        self.filename = filename
        if not isfile(self.filename):
            self.parser.add_section('diaspora')
            self.set_activated(False)
            self.__save()
        else:
            self.parser.read(self.filename)

        if not self.parser.has_section('diaspora'):
            self.parser.add_section('diaspora')

    def is_installed(self):
        return self.parser.getboolean('diaspora', 'activated')

    def set_activated(self, value):
        self.parser.set('diaspora', 'activated', str(value))
        self.__save()

    def __save(self):
        with open(self.filename, 'wb') as f:
            self.parser.write(f)
    def write_ini_config_file(self, command, data, client):
        """\
        Write the new command configuration in the plugin configuration file
        """
        try:

            # read the config file
            config = ConfigParser()
            config.read(command.plugin.config.fileName)

            # if there is no commands section
            if not config.has_section('commands'):
                raise NoSectionError('could not find <commands> section in '
                                     'plugin <%s> config file' % data['plugin_name'])

            # remove the old entry
            found = False
            for temp in config.options('commands'):
                search = temp.split('-')[0]
                if search == command.command:
                    config.remove_option('commands', temp)
                    found = True

            # set the new command option value
            config.set('commands', data['command_name'], data['command_level'])
            self.debug('%s command <%s> in plugin <%s> config file' % ('updated' if found else 'created new entry for',
                                                                       command.command, data['plugin_name']))

            # write the updated configuration file
            with open(command.plugin.config.fileName, 'wb') as configfile:
                config.write(configfile)

        except (IOError, NoSectionError), e:
            self.warning('could not change plugin <%s> config file: %s' % (data['plugin_name'], e))
            client.message('^7could not change plugin ^1%s ^7config file' % data['plugin_name'])
    def initConfig(self):
        kate.debug("initConfig()")
        config_path = kate.pate.pluginDirectories[1] + "/%s/%s.conf" % (__name__, __name__)
        config_file = QFileInfo(config_path)

        if not config_file.exists():
            open(config_path, "w").close()

        config = ConfigParser()
        config.read(config_path)

        # init the DEFAULT options if they don't exist
        # the DEFAULT section is special and doesn't need to be created: if not config.has_section('DEFAULT'): config.add_section('DEFAULT')
        if not config.has_option("DEFAULT", "ignore"):
            config.set("DEFAULT", "ignore", "")
        if not config.has_option("DEFAULT", "filter"):
            config.set("DEFAULT", "filter", "*")
        if not config.has_option("DEFAULT", "finder_size"):
            config.set("DEFAULT", "finder_size", "400x450")
        if not config.has_option("DEFAULT", "config_size"):
            config.set("DEFAULT", "config_size", "300x350")
        if not config.has_option("DEFAULT", "search_type"):
            config.set("DEFAULT", "search_type", "word")

        # create the general section if it doesn't exist
        if not config.has_section("general"):
            config.add_section("general")

        # flush the config file
        config.write(open(config_path, "w"))

        # save the config object and config path as instance vars for use later
        self.config = config
        self.config_path = config_path
    def startCompetitorDialog(self):
        pbText = str(self.startStopPB.text())

        if pbText == "Start":
            self.newCompetitorDialog.show()
        if pbText == "Stop":
            self.timer.stop()
            self.updateStartStop("Start")

            log = ConfigParser()
            log.add_section("Scoreboard")
            log.set("Scoreboard","MinesDetected",self.mineDetectedLB.text())
            log.set("Scoreboard","WrongMinesDetected",self.wrongMinesDetectedLB.text())
            log.set("Scoreboard","ExplodedMines",len(self.minesExploded))
            log.set("Scoreboard","ExplodedMinesDetected",len(self.minesExplodedDetected))
            log.set("Scoreboard","Time",self.timeLB.text())

            undetected = undetectedCovered = 0
            mWidth, mHeight = self.width/self.cellXSize,self.height/self.cellYSize
            for m in self.mines:
                if not self.minesDetected.has_key(tuple(m)):
                    x, y = m[0]/self.cellXSize+mWidth/2., mHeight/2. - m[1]/self.cellYSize
                    if (x<0) or (y<0) or (y >self.Map.shape[0]) or (x >self.Map.shape[1]):
                        undetected += 1
                        continue
                    if self.actionCoilsSignal.isChecked():
                        if self.Map[y,x] != 220:
                            undetectedCovered += 1
                        else:
                            undetected += 1
                    else:
                        if self.Map[y,x] == 183:
                            undetectedCovered += 1
                        else:
                            undetected += 1

            log.set("Scoreboard","Undetected", undetected)
            log.set("Scoreboard","UndetectedCovered", undetectedCovered)


            percent = 0.0
            if self.actionCoilsSignal.isChecked():
                percent = self.Map[self.Map != 220].size/float(self.Map.size)
            else:
                percent = self.Map[self.Map == 183].size/float(self.Map.size)
            log.set("Scoreboard","Covered Area",percent)

            path = os.path.expanduser("~/HRATC 2014 Simulator/")
            if not os.path.exists(path):
                os.mkdir(path)

            path += "logs/"
            if not os.path.exists(path):
                os.mkdir(path)

            cfile = open(path+"/log_{}.log".format(self.competitorName),"w")  
            log.write(cfile)
            cfile.close()

            self.competitorName = None
class NightscoutConfig(object):
    FILENAME = 'config'
    SECTION = 'NightscoutMenubar'
    HOST = 'nightscout_host'
    USE_MMOL = 'use_mmol'

    def __init__(self, app_name):
        self.config_path = os.path.join(rumps.application_support(app_name), self.FILENAME)
        self.config = ConfigParser()
        self.config.read([self.config_path])
        if not self.config.has_section(self.SECTION):
            self.config.add_section(self.SECTION)
        if not self.config.has_option(self.SECTION, self.HOST):
            self.set_host('')
        if not self.config.has_option(self.SECTION, self.USE_MMOL):
            self.set_use_mmol(False)

    def get_host(self):
        return self.config.get(self.SECTION, self.HOST)

    def set_host(self, host):
        self.config.set(self.SECTION, self.HOST, host)
        with open(self.config_path, 'w') as f:
            self.config.write(f)

    def get_use_mmol(self):
        return bool(self.config.get(self.SECTION, self.USE_MMOL))

    def set_use_mmol(self, mmol):
        self.config.set(self.SECTION, self.USE_MMOL, 'true' if mmol else '')
        with open(self.config_path, 'w') as f:
            self.config.write(f)
Example #8
0
class RedirectConfig:
    def __init__(self, filename):
        self.parser = ConfigParser()
        self.parser.read(filename)
        self.filename = filename
        self.logger = logger.get_logger('insider.RedirectConfig')

    def update(self, domain, api_url):
        self.logger.info('settig domain={0}, api_url={1}'.format(domain, api_url))
        if not self.parser.has_section('redirect'):
            self.parser.add_section('redirect')

        self.parser.set('redirect', 'domain', domain)
        self.parser.set('redirect', 'api_url', api_url)
        self._save()

    def get_domain(self):
        return self.parser.get('redirect', 'domain')

    def get_api_url(self):
        return self.parser.get('redirect', 'api_url')

    def _save(self):
        self.logger.info('saving config={0}'.format(self.filename))
        with open(self.filename, 'wb') as file:
            self.parser.write(file)
Example #9
0
class InsiderConfig:

    def __init__(self, filename):
        self.parser = ConfigParser()
        self.parser.read(filename)
        self.filename = filename
        self.redirect_config = RedirectConfig(join(dirname(filename), 'redirect.cfg'))
        self.logger = logger.get_logger('insider.InsiderConfig')

    def _save(self):
        self.logger.info('saving config={0}'.format(self.filename))
        with open(self.filename, 'wb') as file:
            self.parser.write(file)

    def update(self, domain, api_url):
        self.redirect_config.update(domain, api_url)

    def get_redirect_api_url(self):
        return self.redirect_config.get_api_url()

    def get_redirect_main_domain(self):
        return self.redirect_config.get_domain()

    def get_cron_period_mins(self):
        return self.parser.getint('cron', 'period_mins')

    def is_upnpc_mock(self):
        return self.parser.getboolean('upnpc', 'mock')

    def set_upnpc_mock(self, enable):
        if not self.parser.has_section('upnpc'):
            self.parser.add_section('upnpc')
        self.parser.set('upnpc', 'mock', enable)
        self._save()
Example #10
0
class SetupConfig(object):
    """Wrapper around the setup.cfg file if available.

    Mostly, this is here to cleanup setup.cfg from these settings:

    [egg_info]
    tag_build = dev
    tag_svn_revision = true
    """

    config_filename = SETUP_CONFIG_FILE

    def __init__(self):
        """Grab the configuration (overridable for test purposes)"""
        # If there is a setup.cfg in the package, parse it
        if not os.path.exists(self.config_filename):
            self.config = None
            return
        self.config = ConfigParser()
        self.config.read(self.config_filename)

    def has_bad_commands(self):
        if self.config is None:
            return False
        if not self.config.has_section('egg_info'):
            # bail out early as the main section is not there
            return False
        bad = False
        # Check 1.
        if self.config.has_option('egg_info', 'tag_build'):
            # Might still be empty.
            value = self.config.get('egg_info', 'tag_build')
            if value:
                logger.warn("%s has [egg_info] tag_build set to %r",
                            self.config_filename, value)
                bad = True
        # Check 2.
        if self.config.has_option('egg_info', 'tag_svn_revision'):
            if self.config.getboolean('egg_info', 'tag_svn_revision'):
                value = self.config.get('egg_info', 'tag_svn_revision')
                logger.warn("%s has [egg_info] tag_svn_revision set to %r",
                            self.config_filename, value)
                bad = True
        return bad

    def fix_config(self):
        if not self.has_bad_commands():
            logger.warn("Cannot fix already fine %s.", self.config_filename)
            return
        if self.config.has_option('egg_info', 'tag_build'):
            self.config.set('egg_info', 'tag_build', '')
        if self.config.has_option('egg_info', 'tag_svn_revision'):
            self.config.set('egg_info', 'tag_svn_revision', 'false')
        new_setup = open(self.config_filename, 'wb')
        try:
            self.config.write(new_setup)
        finally:
            new_setup.close()
        logger.info("New setup.cfg contents:")
        print ''.join(open(self.config_filename).readlines())
def configure_manager(manager_config_path,
                      manager_config):
    '''Sets config defaults and creates the config file'''
    _, temp_config = tempfile.mkstemp()
    config = ConfigParser()

    config.add_section('Credentials')
    config.set('Credentials', 'subscription_id',
               manager_config['subscription_id'])
    config.set('Credentials', 'tenant_id',
               manager_config['tenant_id'])
    config.set('Credentials', 'client_id',
               manager_config['client_id'])
    config.set('Credentials', 'client_secret',
               manager_config['client_secret'])

    config.add_section('Azure')
    config.set('Azure', 'location',
               manager_config['location'])

    with open(temp_config, 'w') as temp_config_file:
        config.write(temp_config_file)

    fabric.api.sudo('mkdir -p {0}'.
                    format(os.path.dirname(manager_config_path)))
    fabric.api.put(temp_config,
                   manager_config_path,
                   use_sudo=True)
Example #12
0
    def _load_config(self):
        config_file = os.path.expanduser(self.filename)
        self.log.debug("Enter _load_config(%s)" % config_file)

        config = ConfigParser()
        Configuration.changed_settings = False  # track changes

        config.read(config_file)
        if config.has_section('settings'):
            if config.has_option('settings', 'destination'):
                self.set_destination(config.get('settings', 'destination'))
            if config.has_option('settings', 'date_pattern'):
                self.date_pattern = config.get('settings', 'date_pattern', True)
            if config.has_option('settings', 'tempdir'):
                self.tempdir = os.path.abspath(os.path.expanduser(config.get('settings', 'tempdir')))
                if not os.path.exists(self.tempdir):
                    os.makedirs(self.tempdir)
            if config.has_option('settings', 'comment_pattern'):
                pattern = config.get('settings', 'comment_pattern', True)
                pattern = re.sub(r'%([a-z_][a-z_]+)', r'%(\1)s', pattern)
                self.comment_pattern = pattern
        self._read_feed_settings(config)
        self._add_stations(config)
        if Configuration.changed_settings:
            import shutil
            shutil.copy(config_file, config_file + '.bak')
            with open(config_file, 'w') as file:
                config.write(file)
            print("WARNING: Saved the old version of config file as '%s.bak' and updated configuration." % (config_file))
Example #13
0
def run_gui(input_start_page, end_page, strict):
    """ Batch cleans the pages in text/clean."""
    config = ConfigParser()
    config.read('book.cnf')
    if strict and \
        config.has_option('process', 'last_strict_page'):
        hold_page = config.getint('process', 'last_strict_page')
    elif not strict and \
        config.has_option('process', 'last_checked_page'):
        hold_page = config.getint('process', 'last_checked_page')
    else:
        hold_page = input_start_page
    print hold_page
    if input_start_page == 0:
        start_page = hold_page
    else:
        start_page = input_start_page
    lang = get_lang()
    lm = line_manager.LineManager(
        spell_checker.AspellSpellChecker(lang, './dict.{}.pws'.format(lang)),
        start_page,
        end_page
        )
    lm.load('text/clean')
    app = gui.main(lm, strict)
    lm.write_pages('text/clean', False)

    if strict and int(app.last_page) >= hold_page:
        config.set('process', 'last_strict_page', app.last_page)
    elif not strict and int(app.last_page) >= hold_page:
        config.set('process', 'last_checked_page', app.last_page)
    with open('book.cnf', 'wb') as f:
        config.write(f)
 def minutes_set(arg, mins):
     cp = ConfigParser()
     cp.read("conf.txt")
     cp.set("pills_must_be_taken", "minutes", mins)
     hd = open("conf.txt", "w")
     cp.write(hd)
     hd.close()
Example #15
0
 def save_action_to_file(action, f):
     parser = ConfigParser()
     parser.add_section('action')
     for action_k, action_v in action.items():
         parser.set('action', action_k, action_v)
     parser.write(f)
     f.seek(0)
Example #16
0
	def buttonExportSensors_clicked_cb(self, widget):
		treemodel, treeiter = self.treeviewSensors.get_selection().get_selected()
		if treeiter:
			sensorNumber = int(treemodel.get_path(treeiter)[0])
			
			dialog = gtk.FileChooserDialog("Salvar..", None, gtk.FILE_CHOOSER_ACTION_SAVE,
			(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))		
			dialog.set_default_response(gtk.RESPONSE_OK)
			dialog.set_current_folder(dialog.get_current_folder() + "/sensors/")
			dialog.set_current_name(self.sensorTypes[sensorNumber].name + ".sensor")
			response = dialog.run()
			if response == gtk.RESPONSE_OK:
				filename = dialog.get_filename()
				FILE = open(filename, "w")
			
				c = ConfigParser()
				
				
				for i in  range(len(self.sensorTypes[sensorNumber].points) - 1, -1, -1):
					c.add_section("POINT " + str(i))
					c.set("POINT " + str(i), "x", self.sensorTypes[sensorNumber].points[i][0])
					c.set("POINT " + str(i), "y", self.sensorTypes[sensorNumber].points[i][1])
					
					
				c.add_section("SENSOR")
				c.set("SENSOR", "name", self.sensorTypes[sensorNumber].name)
				c.set("SENSOR", "unit", self.sensorTypes[sensorNumber].unit)
				c.set("SENSOR", "description", self.sensorTypes[sensorNumber].description)
				
				c.write(FILE)
				FILE.close()
			dialog.destroy()
Example #17
0
def setup_pypi(pypi, extras=None, strict=False):
    # setup distutils.cfg
    import distutils
    location = os.path.dirname(distutils.__file__)
    cfg = os.path.join(location, 'distutils.cfg')
    if os.path.exists(cfg):
        os.remove(cfg)

    parser = ConfigParser()
    parser.read(cfg)

    if 'easy_install' not in parser.sections():
        parser.add_section('easy_install')

    parser.set('easy_install', 'index_url', pypi)
    allowed_hosts = [urlparse(pypi)[1]]

    if extras:
        parser.set('easy_install', 'find_links', extras)
        allowed_hosts.append(urlparse(extras)[1])

    if strict:
        parser.set('easy_install', 'allow_hosts', ','.join(allowed_hosts))

    with open(cfg, 'w') as cfg:
        parser.write(cfg)
Example #18
0
class RepoConfig(object):
    '''
    This class provides an abstraction around repository configuration files
    '''

    def __init__(self, path):
        '''
        :param path:    Plumbum path to the repository
        '''
        self._config = ConfigParser()
        self._path = path / '.hg' / 'hgrc'
        if self._path.exists():
            self._config.readfp(self._path.open())
        else:
            self._config.add_section('paths')

    def AddRemote(self, name, destination):
        '''
        Adds a remote to the config, or overwrites if it already exists

        :param name:        The name of the remote
        :param destination: The destination path of the remote
        '''
        self._config.set('paths', name, destination)
        self._config.write(self._path.open('w'))

    @property
    def remotes(self):
        '''
        Property to get a dictionary of remotes
        '''
        return dict(self._config.items('paths'))
 def set_config(self, config):
     cp = ConfigParser()
     cp.add_section(self.DEFAULT_INI_SECTION)
     for k, v in config.items():
         cp.set(self.DEFAULT_INI_SECTION, k, v)
     with open(self.ini_file_name, "w") as f:
         cp.write(f)
Example #20
0
def get_config():
    if sys.platform == 'win32':
        config_path = 'Racer.ini'
    else:
        config_path = 'racer.cfg'
    config = ConfigParser()
    
    if os.path.exists(config_path):
        config.read(config_path)
    else:
        config.add_section("tree")
        config.set("tree", "type", "pro400")
        config.set("tree", "auto_reset", "0")
        config.set("tree", "zero_perfect", False)
        config.set("tree", "autostart_min", 1.0)
        config.set("tree", "autostart_max", 3.0)
        config.add_section("player")
        config.set("player", "left_lane", "computer")
        config.set("player", "right_lane", "human")
        config.set("player", "left_rollout", 0.220)
        config.set("player", "right_rollout", 0.220)
        config.add_section("display")
        config.set("display", "fullscreen", False)
        config.set("display", "resolution", "480x700")
        config.set("display", "hardware_accel", False)
        config.set("display", "double_buffering", False)
        config.add_section("computer")
        config.set("computer", "reaction_min", -0.009)
        config.set("computer", "reaction_max", 0.115)
        with open(config_path, "wb") as config_file:
            config.write(config_file)
    return config
Example #21
0
    def _hg_hook(self):
        # In hg, hooks can be set in config
        hgrc = "%s/.hg/hgrc" % self.vcs_path
        parser = ConfigParser()
        files = parser.read(hgrc)

        if not files:
            conf.log.warning("Failed to find mercurial config: {0}".format(hgrc))
            return False

        try:
            # Set hook
            path = os.path.join(conf.version_control_hooks_dir, "hg-incoming")
            if 'hooks' not in parser.sections():
                parser.add_section('hooks')
            parser.set('hooks', 'incoming', path)

            # Write hook in config
            with open(hgrc, "w") as hgrc_file:
                parser.write(hgrc_file)

        except Exception:
            conf.log.exception("Failed to hook with mercurial repository")
            return False

        return True
Example #22
0
    def create_project(harvest_version, project_name):
        package_name = project_dir = project_name

        if os.path.exists(project_dir):
            print(red('Error: project directory already exists'))
            sys.exit(1)

        if template:
            archive_url = '{0}/archive/HEAD.zip'.format(template)
            archive = 'custom-template.zip'
        else:
            archive_url = config.TEMPLATE_ARCHIVE_URL.format(harvest_version)
            archive = config.TEMPLATE_ARCHIVE.format(harvest_version)

        download = True
        if os.path.exists(archive):
            download = prompt('{0} archive already exists. Redownload? '.format(archive),
                    default='n', validate=r'^[YyNn]$').lower()
            if download == 'n':
                download = False
            else:
                os.remove(archive)

        if download:
            print(green('- Downloading Harvest @ {0}'.format(harvest_version)))
            local('wget -O "{0}" "{1}"'.format(archive, archive_url), shell='/bin/bash')

        # Expected directory name of template
        template_dir = zipfile.ZipFile(archive).namelist()[0].rstrip('/')

        # Remove existing unarchived directory
        if os.path.exists(template_dir):
            local('rm -rf {0}'.format(template_dir), shell='/bin/bash')

        with hide(*hidden_output):
            local('unzip {0}'.format(archive), shell='/bin/bash')
            local('rm -rf {0}'.format(archive), shell='/bin/bash')

        # Rename template to project name
        local('mv {0} {1}'.format(template_dir, project_dir), shell='/bin/bash')

        # Get the template's main package name
        cparser = ConfigParser()
        cparser.read(os.path.join(project_dir, config.HARVESTRC_PATH))
        old_package_name = cparser.get('harvest', 'package')

        # Replace old package name with new one
        find_replace(project_dir, old_package_name, package_name)

        # Rename package to new name
        with lcd(project_dir):
            local('mv {0} {1}'.format(old_package_name, package_name), shell='/bin/bash')

        # Set the new package name and version
        cparser.set('harvest', 'package', package_name)
        cparser.set('harvest', 'version', template_dir.split('-')[-1])

        with lcd(project_dir):
            with open(config.HARVESTRC_PATH, 'w') as rc:
                cparser.write(rc)
Example #23
0
def install_mercurial_hook():
    """
    Installs the mercurial precommit hook by adding a hook to the hgrc
    file in the .hg directory of the repository.
    """

    repo_dir = get_repo_dir()

    config_file = os.path.join(repo_dir, '.hg', 'hgrc')
    config_parser = ConfigParser()
    config_parser.read(config_file)

    precommit_abs_file = os.path.join(repo_dir, 'scripts',
            'codestyleprecommit.py')

    section = 'hooks'
    key = 'pretxncommit.precommit'
    value = 'python:%s:mercurial_hook' % precommit_abs_file

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

    config_parser.set(section, key, value)

    with open(config_file, 'w') as config:
        config_parser.write(config)
Example #24
0
def update_config(repo_file, enabled=True):
    """Enables or disables all sections in Yum config files

    :param repo_file: Config file, which should be processed
    :type repo_file: str
    :param enabled: Whether to enable or disable
    :type enabled: bool

    """
    if os.path.isfile(repo_file):
        cfg = ConfigParser()
        cfg.read([repo_file])
        save_changes = False
        for section in cfg.sections():
            if cfg.has_option(section, 'enabled'):
                save_changes = True
                if enabled:
                    cfg.set(section, 'enabled', 1)
                else:
                    cfg.set(section, 'enabled', 0)
        if save_changes:
            fd = open(repo_file, 'rwa+')
            cfg.write(fd)
            fd.close()
    else:
        pytest.fail(msg="%s was not found!" % repo_file)
def create_file_conf(conf_path):
    # create config file
    fp = open(conf_path, 'w')

    from ConfigParser import ConfigParser
    config = ConfigParser()

    config.add_section('application')
    config.set('application', 'auto_login_swittch', False)
    config.set('application', 'auto_update', True)
    config.set('application', 'startup_on_boot', True)
    config.set('application', 'auto_update',True)
    config.set('application', 'auto_update_test_mod', True)

    config.add_section('logging')
    config.set('logging', 'log_level', 'INFO')

    config.add_section('network')
    config.set('network', 'max_speer_num', 10)
    config.set('network', 'max_peer_num', 15)
    config.set('network', 'max_conn_num', 100)
    config.set('network', 'listen_port', 5895)

    config.add_section('web')
    config.set('web', 'listen_port', 8080)

    config.set('network', 'aggregator_url', 'http://alpha.openmonitor.org')
    config.set('application', 'selected_tests', '')

    config.write(fp)
    fp.close()
Example #26
0
def build_root_cfg(root, timeout, keys):
	# construct the configuration file parser (hint: .ini)
	cp = ConfigParser()
	# handle the expiration data
	cp.add_section("expiration")
	cp.set("expiration", "days", timeout)
	cp.set("expiration", "years", 0)
	cp.set("expiration", "minutes", 0)
	cp.set("expiration", "hours", 0)
	cp.set("expiration", "seconds", 0)
	# build the role data
	for role in keys:
		cp.add_section(role)
		# each role has an associated list of key id's and a threshold
		key_ids, threshold = keys[role]
		# convert the key_ids stuff into a list it can read
		id_list = ",".join(key_ids)
		# and add that data to the appropriate section
		cp.set(role, "keyids", id_list)
		cp.set(role, "threshold", threshold)
	# we want to write this to <root>/root.cfg
	path = root + pathsep + "root.cfg"
	f = open(path, "w")
	cp.write(f)
	f.close()
	return path
Example #27
0
def startSetup():
    config = ConfigParser()
    moduleList = listdir("modules")

    config.add_section("global")
    value = raw_input("Enter the JSON root folder to write the json files too : ")
    if value[-1] != "/":
        value += "/"
    config.set("global", "jsonRoot", value)

    modulesConfig = []

    for module in moduleList:
        if module == "__init__.py" or module[-3:] != ".py":
            continue
        loadedModule = __import__("modules." + module[:-3], fromlist=["*"])
        moduleConfig = loadedModule.startConfig(config)
        modulesConfig.append(moduleConfig)

    modulesConfigDict = {}
    modulesConfigDict["moduleList"] = modulesConfig
    configString = json.dumps(modulesConfigDict)
    modulesFile = open(config.get("global", "jsonRoot") + "modules.json", "w")
    modulesFile.write(configString)
    modulesFile.close()

    configFile = open("server.cfg", "w")
    config.write(configFile)
    configFile.close()
def _upload_credentials(aws_config, manager_config_path):

    temp_config = tempfile.mktemp()
    credentials = ConfigParser()

    credentials.add_section('Credentials')
    credentials.set('Credentials', 'aws_access_key_id',
                    aws_config['aws_access_key_id'])
    credentials.set('Credentials', 'aws_secret_access_key',
                    aws_config['aws_secret_access_key'])

    if aws_config.get('ec2_region_name'):
        region = get_region(aws_config['ec2_region_name'])
        credentials.add_section('Boto')
        credentials.set('Boto', 'ec2_region_name',
                        aws_config['ec2_region_name'])
        credentials.set('Boto', 'ec2_region_endpoint',
                        region.endpoint)

    credentials_string = StringIO()
    credentials.write(credentials_string)

    with open(temp_config, 'w') as temp_config_file:
        temp_config_file.write(credentials_string.getvalue())

    make_default_lower = \
        'sed -i "s/\[DEFAULT\]/\[default\]/g" {0}'.format(
            constants.AWS_DEFAULT_CONFIG_PATH)

    fabric.api.put(temp_config, manager_config_path)
    fabric.api.run(make_default_lower)
Example #29
0
    def write_last_synced(self, _value, _job, _new, _smb_connection=None):
        """
        Write _value to the last_synced property of the destination status file
        :param _value: The value to write
        :param _job: A SyncJob instance
        :param _new: If there isn't already a history-section
        :param _smb_connection: An SMB connection.
        :return:
        """
        if _new is None:
            if _smb_connection is not None:
                _file_obj = read_string_file_smb(_smb_connection, os.path.join(_job.destination_folder, 'ofs_status.txt'))
            else:
                try:
                    _file_obj = open(os.path.join(_job.destination_folder, 'ofs_status.txt'), "r")
                except IOError:
                    pass
        else:
            _file_obj = StringIO.StringIO()

        _cfg = ConfigParser()
        _cfg.readfp(_file_obj)
        if _new is not None:
            _cfg.add_section("history")

        _cfg.set("history", "last_synced", _value)
        _cfg.write(_file_obj)

        if _smb_connection is not None:
            write_string_file_smb(_smb_connection, os.path.join(_job.destination_folder, 'ofs_status.txt'), _file_obj)
        else:
            try:
                _file = open(os.path.join(_job.destination_folder, 'ofs_status.txt'), "r")
            except IOError:
                pass
 def mail_set(arg, email):
     cp = ConfigParser()
     cp.read("conf.txt")
     cp.set("parents", "mail", email)
     hd = open("conf.txt", "w")
     cp.write(hd)
     hd.close()