コード例 #1
0
class JsonToConfig(object):
    def __init__(self):
        self.cfw = RawConfigParser()
        self.resources = {}
        self.init_resources()

    def init_resources(self):
        if os.path.exists(resource_path):
            f = open(resource_path, 'r')
            data = f.read()
            f.close()
            if len(data) > 0:
                self.resources = json.loads(data)

    def set_cf(self, service, option):
        item = self.resources[service][option]
        self.cfw.set(service, option, item)

    def main(self):
        # print(self.resources)
        for service in self.resources:
            keys = self.resources[service].keys()
            if len(keys) != 0:
                self.cfw.add_section(service)
                for option in keys:
                    self.set_cf(service, option)
        f = open(config_file_path, 'w')
        self.cfw.write(f)
コード例 #2
0
class ReadConfig:
    """读取配置文件"""
    def __init__(self):
        self.config = RawConfigParser()
        self.config.read(contants.global_conf_file,
                         encoding='utf-8')  #先读取global.conf文件
        switch = self.config.getboolean(
            'switch',
            'on')  #global.conf文件中的switch如果是true就去读取online.conf,相反就去读取test.conf
        if switch:
            self.config.read(contants.online_conf_file, encoding='utf-8')
        else:
            self.config.read(contants.test_conf_file, encoding='utf-8')

    def get_str(self, section, option):
        return self.config.get(section, option)

    def get_int(self, section, option):
        return self.config.getint(section, option)

    def get_float(self, section, option):
        return self.config.getfloat(section, option)

    def get_bool(self, section, option):
        return self.config.getboolean(section, option)

    def write(self, section, option, value):
        self.config.set(section, option, value)
        with open(contants.test_conf_file, 'w') as f:
            self.config.write(f)
コード例 #3
0
 def set(self, section, option, new_value):
     with self.lock:
         if self.callback and self.has_section(section) and self.has_option(section, option):
             old_value = self.get(section, option)
             if not self.callback(section, option, new_value, old_value):
                 raise OperationNotPossibleAtRuntimeException
         RawConfigParser.set(self, section, option, new_value)
コード例 #4
0
    def write(self, config_data, filepath=None):
        """
        Create a dotfile from keyword arguments.

        :param config_data:
            Dict of config settings

        :param filepath:
            (Optional) Path to write
        """
        if filepath is None:
            filepath = self.filepath
        config = RawConfigParser()
        section = constants.SECTION_NAME
        config.add_section(section)

        # Set the config settings
        for key, val in six.iteritems(config_data):
            config.set(section, key, val)

        with open(filepath, 'w') as dotfile:
            config.write(dotfile)

        self.enforce_perms()
        log.debug('wrote %s' % filepath)
コード例 #5
0
ファイル: tests.py プロジェクト: ipartola/groper
    def test_parse_config(self):
        fd, filename = tempfile.mkstemp()
        fp = os.fdopen(fd, 'w')
        try:
            cp = RawConfigParser()
            cp.add_section('sec')
            cp.set('sec', 'foo', 'foo')
            cp.set('sec', 'bar', '-1')
            cp.set('sec', 'baz', '-0.1')
            cp.set('sec', 'hum', 'yes')
            cp.set('sec', 'dum', 'no')

            cp.write(fp)
            fp.close()

            self.define_opt('sec', 'foo')
            self.define_opt('sec', 'bar', type=int)
            self.define_opt('sec', 'baz', type=float)
            self.define_opt('sec', 'hum', type=bool)
            self.define_opt('sec', 'dum', type=bool)

            self.parse_config(filename)
            self.verify_all_options()

            self.assertEqual(self.options.sec.foo, 'foo')
            self.assertEqual(self.options.sec.bar, -1)
            self.assertAlmostEqual(self.options.sec.baz, -0.1)
            self.assertEqual(self.options.sec.hum, True)
            self.assertEqual(self.options.sec.dum, False)
        finally:
            os.unlink(filename)
コード例 #6
0
def _read_from_sections(user, collection_url, permission):
    regex = ConfigParser({'login': user, 'path': collection_url})
    for rights in (INITIAL_RIGHTS, settings.DJRADICALE_RIGHTS):
        for section, values in rights.items():
            if not regex.has_section(section):
                regex.add_section(section)
            for key, value in values.items():
                regex.set(
                    section, key,
                    value % {
                        'login': re.escape(user),
                        'path': re.escape(collection_url),
                    })
    log.LOGGER.debug("Rights type '%s'" % __name__)

    for section in regex.sections():
        re_user = regex.get(section, 'user')
        re_collection = regex.get(section, 'collection')
        log.LOGGER.debug(
            "Test if '%s:%s' matches against '%s:%s' from section '%s'" % (
                user, collection_url, re_user, re_collection, section))
        user_match = re.match(re_user, user)
        if user_match:
            re_collection = re_collection.format(*user_match.groups())
            if re.match(re_collection, collection_url):
                log.LOGGER.debug("Section '%s' matches" % section)
                if permission in regex.get(section, 'permission'):
                    return True
            else:
                log.LOGGER.debug("Section '%s' does not match" % section)
    return False
コード例 #7
0
ファイル: config.py プロジェクト: lowks/coal
 def write(self, fp):
     parser = RawConfigParser()
     for section in self:
         parser.add_section(section)
         for key, value in self.items(section):
             parser.set(section, key, value)
     parser.write(fp)
コード例 #8
0
ファイル: init.py プロジェクト: mgukov/gitosis
def init_admin_repository(
    git_dir,
    pubkey,
    user,
):
    repository.init(path=git_dir,
                    template=resource_filename('gitosis.templates', 'admin'))
    repository.init(path=git_dir, )

    # can't rely on setuptools and all kinds of distro packaging to
    # have kept our templates executable, it seems
    os.chmod(os.path.join(git_dir, 'hooks', 'post-update'), 0o755)

    if not repository.has_initial_commit(git_dir):
        log.info('Making initial commit...')
        # ConfigParser does not guarantee order, so jump through hoops
        # to make sure [gitosis] is first
        cfg_file = StringIO()
        print('[gitosis]', file=cfg_file)
        #print('', end="", file=cfg_file)

        #print >>cfg_file, '[gitosis]'
        #print >>cfg_file
        cfg = RawConfigParser()
        cfg.add_section('group gitosis-admin')
        cfg.set('group gitosis-admin', 'members', user)
        cfg.set('group gitosis-admin', 'writable', 'gitosis-admin')
        cfg.write(cfg_file)
        initial_commit(
            git_dir=git_dir,
            cfg=cfg_file.getvalue(),
            pubkey=pubkey,
            user=user,
        )
コード例 #9
0
def test_no_notListed():
    cfg = RawConfigParser()
    cfg.add_section('group hackers')
    cfg.set('group hackers', 'members', 'wsmith')
    gen = group.getMembership(config=cfg, user='******')
    eq(gen.next(), 'all')
    assert_raises(StopIteration, gen.next)
コード例 #10
0
    def test_parse_config(self):
        fd, filename = tempfile.mkstemp()
        fp = os.fdopen(fd, 'w')
        try:
            cp = RawConfigParser()
            cp.add_section('sec')
            cp.set('sec', 'foo', 'foo')
            cp.set('sec', 'bar', '-1')
            cp.set('sec', 'baz', '-0.1')
            cp.set('sec', 'hum', 'yes')
            cp.set('sec', 'dum', 'no')

            cp.write(fp)
            fp.close()

            self.define_opt('sec', 'foo')
            self.define_opt('sec', 'bar', type=int)
            self.define_opt('sec', 'baz', type=float)
            self.define_opt('sec', 'hum', type=bool)
            self.define_opt('sec', 'dum', type=bool)

            self.parse_config(filename)
            self.verify_all_options()

            self.assertEqual(self.options.sec.foo, 'foo')
            self.assertEqual(self.options.sec.bar, -1)
            self.assertAlmostEqual(self.options.sec.baz, -0.1)
            self.assertEqual(self.options.sec.hum, True)
            self.assertEqual(self.options.sec.dum, False)
        finally:
            os.unlink(filename)
コード例 #11
0
ファイル: archiver.py プロジェクト: ReimarBauer/borg
 def _set_repository_id(self, path, id):
     config = RawConfigParser()
     config.read(os.path.join(path, "config"))
     config.set("repository", "id", hexlify(id).decode("ascii"))
     with open(os.path.join(path, "config"), "w") as fd:
         config.write(fd)
     return Repository(self.repository_path).id
コード例 #12
0
ファイル: config.py プロジェクト: kmohrf/vmm
    def set(self, option, value):
        """Set the value of an option.

        If the new `value` has been set, the configuration file will be
        immediately updated.

        Throws a ``ConfigError`` if `value` couldn't be converted to
        ``LazyConfigOption.cls`` or ``LazyConfigOption.validate`` fails."""
        section, option_ = self._get_section_option(option)
        try:
            val = self._cfg[section][option_].cls(value)
            if self._cfg[section][option_].validate:
                val = self._cfg[section][option_].validate(val)
        except (ValueError, ConfigValueError) as err:
            raise ConfigError(str(err), CONF_ERROR)
        # Do not write default values also skip identical values
        if not self._cfg[section][option_].default is None:
            old_val = self.dget(option)
        else:
            old_val = self.pget(option)
        if val == old_val:
            return
        if not RawConfigParser.has_section(self, section):
            self.add_section(section)
        RawConfigParser.set(self, section, option_, val)
        self._save_changes()
コード例 #13
0
ファイル: npr_utils.py プロジェクト: tanimislam/nprstuff
def store_waitwait_downloaddir(waitwait_downloaddir):
    """
    Stores the default location of the `NPR Fresh Air`_ episodes into the configuration file, ``~/.config/nprstuff/nprstuff.com``, into the ``NPR_DATA`` section and ``waitwait_downloaddir`` key.

    :param str waitwait_downloaddir: the default directory to download `NPR Fresh Air`_ episodes.
    
    .. seealso:: :py:meth:`get_waitwait_downloaddir <nprstuff.core.npr_utils.get_waitwait_downloaddir>`.
    """
    assert (os.path.isdir(os.path.abspath(waitwait_downloaddir)))
    resource = 'nprstuff'
    filename = '%s.conf' % resource
    baseConfDir = os.path.abspath(os.path.expanduser('~/.config/%s' %
                                                     resource))
    absPath = os.path.join(baseConfDir, filename)
    if os.path.isdir(absPath):
        shutil.rmtree(absPath)
    if not os.path.isfile(absPath):
        cparser = RawConfigParser()
    else:
        cparser = ConfigParser()
        cparser.read(absPath)
    if 'NPR_DATA' not in cparser.sections():
        cparser.add_section('NPR_DATA')
    cparser.set('NPR_DATA', 'waitwait_downloaddir',
                os.path.abspath(waitwait_downloaddir))
    with open(absPath, 'w') as openfile:
        cparser.write(openfile)
        os.chmod(absPath, 0o600)
コード例 #14
0
ファイル: pwm.py プロジェクト: afflux/pwm
    def run_setup(self, config_file):
        print(textwrap.dedent("""\
            Hi, it looks like it's the first time you're using pwm on this machine. Let's take a little
            moment to set things up before we begin."""))
        db_uri = input('Which database do you want to use (default: local sqlite at ~/.pwm/db.sqlite) ').strip() or 'local'
        rc_dir = os.path.dirname(config_file)

        if db_uri == 'local':

            # normalize windows-style paths for sqlalchemy:
            rc_dir = rc_dir.replace('\\', '/')

            # Create the local database
            db_uri = 'sqlite:///%s/db.sqlite' % rc_dir
        if not '://' in db_uri:
            # Not a sqlalchemy-compatible connection string or https URI, assume it's a local path and make a sqlite
            # uri out of it
            db_uri = 'sqlite:///%s' % db_uri
        if not (db_uri.startswith('https:') or db_uri.startswith('http:')):
            # It's a local db, make sure our tables exist
            db = sa.create_engine(db_uri)
            Base.metadata.create_all(db)

        config_parser = RawConfigParser()
        config_parser.add_section('pwm')
        config_parser.set('pwm', 'database', db_uri)

        with open(config_file, 'w') as config_file_fh:
            config_parser.write(config_file_fh)
コード例 #15
0
ファイル: cfgparser.py プロジェクト: tubbyK/cfgparser
def add_section(filename: str, section: str, data: {}):
    config = RawConfigParser()
    config.add_section(section)
    for key, value in data.items():
        config.set(section, key, value)
    with open(filename, 'a+') as cfgfile:
        config.write(cfgfile)
コード例 #16
0
ファイル: functions_process.py プロジェクト: yusipeng/javsdt
def collect_sculpture(actors, root_now):
    for each_actor in actors:
        path_exist_actor = '演员头像' + sep + each_actor[
            0] + sep + each_actor  # 事先准备好的演员头像路径
        if exists(path_exist_actor + '.jpg'):
            pic_type = '.jpg'
        elif exists(path_exist_actor + '.png'):
            pic_type = '.png'
        else:
            config_actor = RawConfigParser()
            config_actor.read('【缺失的演员头像统计For Kodi】.ini', encoding='utf-8-sig')
            try:
                each_actor_times = config_actor.get('缺失的演员头像', each_actor)
                config_actor.set("缺失的演员头像", each_actor,
                                 str(int(each_actor_times) + 1))
            except:
                config_actor.set("缺失的演员头像", each_actor, '1')
            config_actor.write(
                open('【缺失的演员头像统计For Kodi】.ini', "w", encoding='utf-8-sig'))
            continue
        # 已经收录了这个演员头像
        root_dest_actor = root_now + sep + '.actors' + sep  # 头像的目标文件夹
        if not exists(root_dest_actor):
            makedirs(root_dest_actor)
        # 复制一份到“.actors”
        copyfile(path_exist_actor + pic_type,
                 root_dest_actor + each_actor + pic_type)
        print('    >演员头像收集完成:', each_actor)
コード例 #17
0
 def collect_sculpture(self, list_actors, dir_current):
     if handler.bool_sculpture and jav_file.episode == 1:
         if jav_model.Actors[0] == '有码演员':
             print('    >未知演员,无法收集头像')
         else:
             for each_actor in list_actors:
                 path_exist_actor = f'演员头像{sep}{each_actor[0]}{sep}{each_actor}'  # 事先准备好的演员头像路径
                 if os.path.exists(f'{path_exist_actor}.jpg'):
                     pic_type = '.jpg'
                 elif os.path.exists(f'{path_exist_actor}.png'):
                     pic_type = '.png'
                 else:
                     config_actor = RawConfigParser()
                     config_actor.read('【缺失的演员头像统计For Kodi】.ini',
                                       encoding='utf-8-sig')
                     try:
                         each_actor_times = config_actor.get(
                             '缺失的演员头像', each_actor)
                         config_actor.set("缺失的演员头像", each_actor,
                                          str(int(each_actor_times) + 1))
                     except:
                         config_actor.set("缺失的演员头像", each_actor, '1')
                     config_actor.write(
                         open('【缺失的演员头像统计For Kodi】.ini',
                              "w",
                              encoding='utf-8-sig'))
                     continue
                 # 已经收录了这个演员头像
                 dir_dest_actor = f'{dir_current}{sep}.actors{sep}'  # 头像的目标文件夹
                 if not os.path.exists(dir_dest_actor):
                     os.makedirs(dir_dest_actor)
                 # 复制一份到“.actors”
                 copyfile(f'{path_exist_actor}{pic_type}',
                          f'{dir_dest_actor}{each_actor}{pic_type}')
                 print('    >演员头像收集完成:', each_actor)
コード例 #18
0
ファイル: options.py プロジェクト: GovanifY/PyTouhou
class Options:
    def __init__(self, name, defaults):
        load_paths = list(reversed([os.path.join(directory, '%s.cfg' % name)
                                    for directory
                                    in load_config_paths(name)]))
        self.save_path = os.path.join(save_config_path(name), '%s.cfg' % name)

        self.config = RawConfigParser(defaults)
        self.paths = self.config.read(load_paths)
        self.section = name if self.config.has_section(name) else 'DEFAULT'

    def get(self, option):
        try:
            return self.config.get(self.section, option)
        except NoOptionError:
            return None

    def set(self, option, value):
        if value is not None:
            self.config.set(self.section, option, value)
        else:
            self.config.remove_option(self.section, option)

        defaults = self.config._defaults
        self.config._defaults = None
        with open(self.save_path, 'w') as save_file:
            self.config.write(save_file)
        self.config._defaults = defaults
コード例 #19
0
ファイル: archiver.py プロジェクト: sotte/borg
 def _set_repository_id(self, path, id):
     config = RawConfigParser()
     config.read(os.path.join(path, 'config'))
     config.set('repository', 'id', hexlify(id).decode('ascii'))
     with open(os.path.join(path, 'config'), 'w') as fd:
         config.write(fd)
     return Repository(self.repository_path).id
コード例 #20
0
def create_storage_account(storagename,
                           resource_group_name,
                           location_storage='westeurope',
                           sku='Standard_LRS',
                           storage_kind='StorageV2',
                           config_name='default',
                           saveconfig=True):

    file_path = os.path.join(os.getcwd(),
                             'batch_files\create_storage_account.bat')
    os.system("C:\Windows\System32\cmd.exe /c " + file_path + ' ' +
              storagename + ' ' + resource_group_name + ' ' +
              location_storage + ' ' + sku + ' ' + storage_kind)

    if saveconfig == True:
        if not os.path.exists("config"):
            os.mkdir("config")
        print(
            "Saving Configuration to config/blob.ini \n Please Keep This File Secure."
        )
        config = RawConfigParser()
        config.read('config/blob.ini')
        config.add_section(config_name)
        config.set(config_name, 'storagename', storagename)
        config.set(config_name, 'resource_group_name', resource_group_name)
        config.set(config_name, 'location_storage', location_storage)
        config.set(config_name, 'sku', sku)
        config.set(config_name, 'storage_kind', storage_kind)
        with open('config/blob.ini', 'w') as f:
            config.write(f)
コード例 #21
0
ファイル: config.py プロジェクト: Perdu/poezio
 def set_and_save(self, option, value, section=DEFSECTION):
     """
     set the value in the configuration then save it
     to the file
     """
     # Special case for a 'toggle' value. We take the current value
     # and set the opposite. Warning if the no current value exists
     # or it is not a bool.
     if value == "toggle":
         current = self.get(option, "", section)
         if isinstance(current, bool):
             value = str(not current)
         else:
             if current.lower() == "false":
                 value = "true"
             elif current.lower() == "true":
                 value = "false"
             else:
                 return (_('Could not toggle option: %s.'
                           ' Current value is %s.') %
                               (option, current or _("empty")),
                         'Warning')
     if self.has_section(section):
         RawConfigParser.set(self, section, option, value)
     else:
         self.add_section(section)
         RawConfigParser.set(self, section, option, value)
     if not self.write_in_file(section, option, value):
         return (_('Unable to write in the config file'), 'Error')
     return ("%s=%s" % (option, value), 'Info')
コード例 #22
0
def update_config(path, section, values):
    """
    Function to update config file.

    :param path: Path to config file
    :type: str
    :param section: Config section
    :type: str
    :param values: Dict with new values
    :type: dict
    :return: True or False
    :rtype: bool
    """

    cfg = RawConfigParser()

    if os.path.exists(path):
        cfg.read(path)
        for opt, val in values.items():
            cfg.set(section, opt, val)
        try:
            with open(path, 'w') as config_file:
                cfg.write(config_file)
                return True
        except PermissionError:
            return False
コード例 #23
0
    def run_setup(self, config_file):
        print(
            textwrap.dedent("""\
            Hi, it looks like it's the first time you're using pwm on this machine. Let's take a little
            moment to set things up before we begin."""))
        db_uri = input(
            'Which database do you want to use (default: local sqlite at ~/.pwm/db.sqlite) '
        ).strip() or 'local'
        rc_dir = os.path.dirname(config_file)

        if db_uri == 'local':

            # normalize windows-style paths for sqlalchemy:
            rc_dir = rc_dir.replace('\\', '/')

            # Create the local database
            db_uri = 'sqlite:///%s/db.sqlite' % rc_dir
        if not '://' in db_uri:
            # Not a sqlalchemy-compatible connection string or https URI, assume it's a local path and make a sqlite
            # uri out of it
            db_uri = 'sqlite:///%s' % db_uri
        if not (db_uri.startswith('https:') or db_uri.startswith('http:')):
            # It's a local db, make sure our tables exist
            db = sa.create_engine(db_uri)
            Base.metadata.create_all(db)

        config_parser = RawConfigParser()
        config_parser.add_section('pwm')
        config_parser.set('pwm', 'database', db_uri)

        with open(config_file, 'w') as config_file_fh:
            config_parser.write(config_file_fh)
コード例 #24
0
ファイル: archiver.py プロジェクト: pszxzsd/borg
 def _set_repository_id(self, path, id):
     config = RawConfigParser()
     config.read(os.path.join(path, 'config'))
     config.set('repository', 'id', hexlify(id).decode('ascii'))
     with open(os.path.join(path, 'config'), 'w') as fd:
         config.write(fd)
     return Repository(self.repository_path).id
コード例 #25
0
def _init_config_parser():
    """
    Creates the RawConfigParser object, adds the fields and fills with default/empty values
    :return:
    """
    global _conf_parser
    # Create a new config parser
    _conf_parser = RawConfigParser()
    # Put all options under a Settings Header
    _conf_parser.add_section("Settings")

    # Create defaults tuple
    SettingsDefault = namedtuple('SettingsDefault',
                                 ['setting', 'default_value'])
    default_settings = [
        SettingsDefault._make(["client_id", ""]),
        SettingsDefault._make(["client_secret", ""]),
        SettingsDefault._make(["username", ""]),
        SettingsDefault._make(["password", ""]),
        SettingsDefault._make(["base_url", ""]),
        SettingsDefault._make(["parser", "directory"])
    ]
    # add defaults to config parser
    for config in default_settings:
        _conf_parser.set("Settings", config.setting, config.default_value)
コード例 #26
0
ファイル: milc.py プロジェクト: clueboard/milc
    def _save_config_file(self, config):
        """Write config to disk.
        """
        # Generate a sanitized version of our running configuration
        sane_config = RawConfigParser()
        for section_name, section in config.items():
            sane_config.add_section(section_name)
            for option_name, value in section.items():
                if self.config_source[section_name][
                        option_name] == 'config_file' and value is not None:
                    sane_config.set(section_name, option_name, str(value))

        if not self.config_dir.exists():
            self.config_dir.mkdir(parents=True, exist_ok=True)

        # Write the config file atomically.
        self.acquire_lock()
        with NamedTemporaryFile(mode='w',
                                dir=str(self.config_dir),
                                delete=False) as tmpfile:
            sane_config.write(tmpfile)

        if os.path.getsize(tmpfile.name) > 0:
            os.replace(tmpfile.name, str(self.config_file))
        else:
            self.log.warning(
                'Config file saving failed, not replacing %s with %s.',
                str(self.config_file), tmpfile.name)
        self.release_lock()
コード例 #27
0
ファイル: release.py プロジェクト: boquinr6/my_sanic
def _update_release_version_for_sanic(current_version, new_version,
                                      config_file):
    config_parser = RawConfigParser()
    with open(config_file) as cfg:
        config_parser.read_file(cfg)
    config_parser.set("version", "current_version", new_version)

    version_file = config_parser.get("version", "file")
    current_version_line = config_parser.get(
        "version",
        "current_version_pattern").format(current_version=current_version)
    new_version_line = config_parser.get(
        "version", "new_version_pattern").format(new_version=new_version)

    with open(version_file) as init_file:
        data = init_file.read()

    new_data = data.replace(current_version_line, new_version_line)
    with open(version_file, "w") as init_file:
        init_file.write(new_data)

    with open(config_file, "w") as config:
        config_parser.write(config)

    command = GIT_COMMANDS.get("commit_version_change")
    command[0] = command[0].format(new_version=new_version,
                                   current_version=current_version)
    _, err, ret = _run_shell_command(command)
    if int(ret) != 0:
        print("Failed to Commit Version upgrade changes to Sanic: {}".format(
            err.decode("utf-8")))
        exit(1)
コード例 #28
0
    def test_clean_no_extension(self):
        repo = self.make_clone("clone to clean", "default")
        rc_path = os.path.join(repo.target_dir, ".hg", "hgrc")

        # make sure that 'purge' extension is NOT activated
        # we expect it to be installed on the system this test runs
        # note that that's the case with Debian and Red Hat families of
        # distributions
        parser = RawConfigParser()
        parser.read(rc_path)
        parser.add_section("extensions")
        parser.set("extensions", "hgext.purge", "!")
        with open(rc_path, "w") as rc:
            parser.write(rc)

        dirty_dir = os.path.join(repo.target_dir, "dirty")
        os.mkdir(dirty_dir)
        dirty_files = (
            os.path.join(repo.target_dir, "untracked.pyc"),
            os.path.join(dirty_dir, "untracked2.pyo"),
        )
        for path in dirty_files:
            with open(path, "w") as f:
                f.write("content")
        repo.clean()
        for path in dirty_files:
            self.assertFalse(
                os.path.exists(path),
                "Untracked file %r should have been removed" % path,
            )
        self.assertFalse(os.path.exists(dirty_dir),
                         "Untracked dir should have been removed")
コード例 #29
0
def save_jwt_token(token, expiration=None, path=None):
    """
    Saves JWT token in the config file.
    """
    # Default to ~/.htrc
    if path is None:
        path = DEFAULT_PATH

    # Default to expiration of now - force a new token on next request
    if expiration is None:
        expiration = time.time()

    # Open and modify existing config file, if it exists.
    config = ConfigParser(allow_no_value=True)
    if os.path.exists(path):
        config.read(path)
    if not config.has_section('jwt'):
        config.add_section('jwt')

    # set token and expiration
    config.set('jwt', 'token', token)
    config.set('jwt', 'expiration', expiration)

    with open(path, 'w') as credential_file:
        config.write(credential_file)

    return token
コード例 #30
0
def _init_config_parser():
    """
    Creates the RawConfigParser object, adds the fields and fills with default/empty values
    :return:
    """
    global _conf_parser
    # Create a new config parser
    _conf_parser = RawConfigParser()
    # Put all options under a Settings Header
    _conf_parser.add_section("Settings")

    # Create defaults tuple
    SettingsDefault = namedtuple('SettingsDefault',
                                 ['setting', 'default_value'])
    default_settings = [
        SettingsDefault._make(["client_id", ""]),
        SettingsDefault._make(["client_secret", ""]),
        SettingsDefault._make(["username", ""]),
        SettingsDefault._make(["password", ""]),
        SettingsDefault._make(["base_url", ""]),
        SettingsDefault._make(["parser", "directory"]),
        SettingsDefault._make(["readonly", False]),
        SettingsDefault._make(["delay", 0]),
        SettingsDefault._make(
            ["timeout", 10]),  # default timeout scale is 10 seconds per mb
        SettingsDefault._make(["minimum_file_size", 0])
    ]  # default minimum file size in kb
    # add defaults to config parser
    for config in default_settings:
        _conf_parser.set("Settings", config.setting, config.default_value)
コード例 #31
0
    def authorized(self, user, path, permission):
        # collection_url = collection.url.rstrip('/') or '/'
        # if collection_url in ('.well-known/carddav', '.well-known/caldav'):
        #     return permission == 'r'
        # return _read_from_sections(user or '', collection_url, permission)

        regex = ConfigParser({'login': user, 'path': path})
        for rights in (INITIAL_RIGHTS, settings.DJRADICALE_RIGHTS):
            for section, values in rights.items():
                if not regex.has_section(section):
                    regex.add_section(section)
                for key, value in values.items():
                    regex.set(
                        section, key, value % {
                            'login': re.escape(user),
                            'path': re.escape(path),
                        })
        self.logger.debug("Rights type '%s'" % __name__)

        for section in regex.sections():
            re_user = regex.get(section, 'user')
            re_collection = regex.get(section, 'collection')
            log.LOGGER.debug(
                "Test if '%s:%s' matches against '%s:%s' from section '%s'" %
                (user, path, re_user, re_collection, section))
            user_match = re.match(re_user, user)
            if user_match:
                re_collection = re_collection.format(*user_match.groups())
                if re.match(re_collection, path):
                    self.logger.debug("Section '%s' matches" % section)
                    if permission in regex.get(section, 'permission'):
                        return True
                else:
                    self.logger.debug("Section '%s' does not match" % section)
        return False
コード例 #32
0
class ConfigHandler:
    def __init__(self, file_name):
        self.conf = RawConfigParser()
        self.file_name = os.path.join(conf_loc, file_name)
        self.conf.read(self.file_name, encoding='utf-8')

    def get_sections(self):
        """获取所有的sections"""
        return self.conf.sections()

    def get_options(self, section):
        """获取section下所有的option"""
        return self.conf.options(section)

    def read(self, section, option):
        """读取section,下option的值"""
        return self.conf.get(section, option)

    def write(self, section, option, value):
        """1、判断该片段是否存在,不存在新增加一个节点
           2、该节点存在的话,如果键存在,更新值
           3、键不存在,新增一个键,并为其赋值
        """
        if not self.conf.has_section(section):
            self.conf.add_section(section)
        self.conf.set(section, option, value)
        with open(self.file_name, 'w', encoding='utf-8') as f:
            self.conf.write(f)

    def return_data(self, section, option):
        """将查询到的数据范围为原类型"""
        result = self.read(section, option)
        return eval(result)
コード例 #33
0
ファイル: config.py プロジェクト: zhangjinbao520/BaWangCan
class Config(object):
    def __init__(self, file='config.ini'):
        super().__init__()
        self.file = file
        self.config = RawConfigParser()
        self.config.read(self.file, encoding='utf-8')  # 读取文件

    def getConfig(self, section, option):
        '''
        读取config.ini配置文件
        '''
        try:
            return self.config.get(section, option)
        except:
            return None

    def saveConfig(self, section, option, value=None):
        '''
        保存config.ini配置文件
        '''
        try:
            self.config.add_section(section)  # 如果键值不存在,则创建键值
        except:
            pass
        self.config.set(section, option, value)
        self.config.write(open(self.file, "w+",
                               encoding='utf-8'))  # 写入文件(读写模式)
コード例 #34
0
 def set_and_save(self,
                  option: str,
                  value: ConfigValue,
                  section=DEFSECTION) -> Tuple[str, str]:
     """
     set the value in the configuration then save it
     to the file
     """
     # Special case for a 'toggle' value. We take the current value
     # and set the opposite. Warning if the no current value exists
     # or it is not a bool.
     if value == "toggle":
         current = self.get(option, "", section)
         if isinstance(current, bool):
             value = str(not current)
         else:
             if current.lower() == "false":
                 value = "true"
             elif current.lower() == "true":
                 value = "false"
             else:
                 return ('Could not toggle option: %s.'
                         ' Current value is %s.' %
                         (option, current or "empty"), 'Warning')
     if self.has_section(section):
         RawConfigParser.set(self, section, option, value)
     else:
         self.add_section(section)
         RawConfigParser.set(self, section, option, value)
     if not self.write_in_file(section, option, value):
         return ('Unable to write in the config file', 'Error')
     return ("%s=%s" % (option, value), 'Info')
コード例 #35
0
def saveConfigini():
    parser = RawConfigParser()
    parser.add_section('GPORTAL')
    for key in configini.keys():
        parser.set('GPORTAL', key, configini[key])
    with open('scumlogs.ini', 'w', encoding="utf-8") as f:
        parser.write(f)
コード例 #36
0
ファイル: conftest.py プロジェクト: thesquelched/suggestive
def mock_config(config_dir):
    data = dict(
        general=dict(
            conf_dir=config_dir,
            verbose=True,
            update_on_startup=False,
        ),
        mpd=dict(
            host='localhost',
            port=6600,
        ),
        lastfm=dict(
            scrobble_days=180,
            user='******',
            api_key='apikey',
            api_secret='secret',
        ),
    )
    config = RawConfigParser()
    for section, options in data.items():
        config.add_section(section)
        for key, value in options.items():
            config.set(section, key, value)

    with NamedTemporaryFile(mode='w') as temp:
        config.write(temp)
        temp.flush()

        with patch('suggestive.config.CONFIG_PATHS', [temp.name]):
            return Config()
コード例 #37
0
ファイル: config.py プロジェクト: labedz/poezio
 def set(self, option, value, section=DEFSECTION):
     """
     Set the value of an option temporarily
     """
     try:
         RawConfigParser.set(self, section, option, value)
     except NoSectionError:
         pass
コード例 #38
0
ファイル: endtoend_test.py プロジェクト: gryphius/fuglu
    def setUp(self):
        config = RawConfigParser()
        config.read([CONFDIR + '/fuglu.conf.dist'])
        config.set('main', 'disablebounces', '1')
        guess_clamav_socket(config)

        self.mc = MainController(config)
        self.tempfiles = []
コード例 #39
0
ファイル: plugins_sa_test.py プロジェクト: Caomhin/fuglu
 def setUp(self):
     config = RawConfigParser()
     config.add_section('main')
     config.set('main', 'disablebounces', '1')
     config.add_section('SAPlugin')
     # current tests don't need config options, add them here later if
     # necessary
     self.config = config
コード例 #40
0
    def save_auth(self, username, password):
        """"""
        parser = RawConfigParser()
        parser.add_section("AUTH")
        parser.set("AUTH", "username", username)
        parser.set("AUTH", "password", password)

        filename = os.path.join(os.getenv("PINGUINO_USER_PATH"), "submit-auth")
        parser.write(open(filename, "w"))
コード例 #41
0
ファイル: dogtaginstance.py プロジェクト: tiran/freeipa
    def create_spawn_config(self, subsystem_config):
        """Create config instance
        """
        section_name = self.defaults['pki_subsystem']
        cfgtpl, immutable_keys = self._get_default_config()

        # overwrite CA/KRA config with subsystem settings
        subsystem_config = self._mangle_values(subsystem_config)
        for key, value in subsystem_config.items():
            cfgtpl.set(section_name, key, value)

        # get a mapping of settings that cannot be modified by users
        immutable_settings = {
            k: v for k, v in cfgtpl.items(section_name)
            if k in immutable_keys
        }

        # add ipaca_customize overlay,
        # These are settings that can be modified by a user, too. We use
        # ipaca_customize.ini to set sensible defaults.
        with open(self.ipaca_customize) as f:
            cfgtpl.read_file(f)

        # load external overlay from command line
        if self.pki_config_override is not None:
            with open(self.pki_config_override) as f:
                cfgtpl.read_file(f)

        # verify again
        self._verify_immutable(
            cfgtpl, immutable_settings, self.pki_config_override
        )

        # key backup is not compatible with HSM support
        if (cfgtpl.has_option(section_name, 'pki_hsm_enable') and
                cfgtpl.getboolean(section_name, 'pki_hsm_enable')):
            cfgtpl.set(section_name, 'pki_backup_keys', 'False')
            cfgtpl.set(section_name, 'pki_backup_password', '')

        pki_token_name = cfgtpl.get(section_name, 'pki_token_name')
        for stanza in self.token_stanzas:
            if cfgtpl.has_option(section_name, stanza):
                cfgtpl.set(section_name, stanza, pki_token_name)

        # Next up, get rid of interpolation variables, DEFAULT,
        # irrelevant sections and unused variables. Only the subsystem
        # section is copied into a new raw config parser. A raw config
        # parser is necessary, because ConfigParser.write() write passwords
        # with '%' in a way, that is not accepted by Dogtag.
        config = RawConfigParser()
        config.optionxform = str
        config.add_section(section_name)
        for key, value in sorted(cfgtpl.items(section=section_name)):
            if key.startswith('pki_'):
                config.set(section_name, key, value)

        return config
コード例 #42
0
ファイル: helper_config.py プロジェクト: SimoWhatsup/pysurvey
    def write_config(self, survey_dict=None, mosaic_dict=None, constants_dict=None, spectral_dict=None,
                     spatial_dict=None):
        """
        Writes all of the needed information to the config file called <mosaicname>.cfg
        """
        if not os.path.isdir(SURVEY_CONFIG_DIR):
            os.makedirs(SURVEY_CONFIG_DIR)
        configfilename = survey_dict['survey'] + '_' + mosaic_dict['mosaic']

        config = RawConfigParser()
        config.read(configfilename + '.cfg')
        if not config.has_section('survey'):
            config.add_section('survey')

        for variable, value in survey_dict.items():
            config.set('survey', variable, value)
        self.logger.info('wrote common config to ' + configfilename + '.cfg.')

        if mosaic_dict:
            if config.has_section('mosaic'):
                self.logger.info("mosaic config exists, overwriting...")
            else:
                config.add_section('mosaic')
            for variable, value in mosaic_dict.items():
                config.set('mosaic', variable, value)
            self.logger.info("wrote mosaic config to " + configfilename + ".cfg.")

        if constants_dict:
            if config.has_section('constants'):
                self.logger.info("constants config exists, overwriting...")
            else:
                config.add_section('constants')
            for variable, value in constants_dict.items():
                config.set('constants', variable, value)
            self.logger.info("wrote constants config to " + configfilename + ".cfg.")

        if spectral_dict:
            if config.has_section('spectralSearch'):
                self.logger.info("spectralSearch config exists, overwriting...")
            else:
                config.add_section('spectralSearch')
            for variable, value in spectral_dict.items():
                config.set('spectralSearch', variable, value)
            self.logger.info("wrote spectralSearch config to " + configfilename + ".cfg.")

        if spatial_dict:
            if config.has_section('spatialSearch'):
                self.logger.info("spatialSearch config exists, overwriting...")
            else:
                config.add_section('spatialSearch')
            for variable, value in spatial_dict.items():
                config.set('spatialSearch', variable, value)
            self.logger.info("wrote spatialSearch config to " + configfilename + ".cfg.")

        with open(SURVEY_CONFIG_DIR + configfilename + '.cfg', 'w') as configfile:
            config.write(configfile)
コード例 #43
0
ファイル: config.py プロジェクト: Perdu/poezio
 def silent_set(self, option, value, section=DEFSECTION):
     """
     Set a value, save, and return True on success and False on failure
     """
     if self.has_section(section):
         RawConfigParser.set(self, section, option, value)
     else:
         self.add_section(section)
         RawConfigParser.set(self, section, option, value)
     return self.write_in_file(section, option, value)
コード例 #44
0
ファイル: config.py プロジェクト: davisd/Radicale
def load(paths=()):
    config = ConfigParser()
    for section, values in INITIAL_CONFIG.items():
        config.add_section(section)
        for key, value in values.items():
            config.set(section, key, value)
    for path in paths:
        if path:
            config.read(path)
    return config
コード例 #45
0
ファイル: GPIOSim.py プロジェクト: ekapujiw2002/GPIOSim
    def updateFile(self):
        c = RawConfigParser()
        c.read(self.WORK_FILE)

        for i in range(0,40):
            c.set("pin"+str(i),"state",str(self.currState[i]))
            c.set("pin"+str(i),"value",str(self.currValue[i]))

        with open(self.WORK_FILE, 'w') as configfile:
            c.write(configfile)
コード例 #46
0
ファイル: helpers.py プロジェクト: grampajoe/selenose
def get_base_env(cls, name, section, options=None, server=None):
    '''
    Get a base environment.
    '''
    options = options or {}
    parser = RawConfigParser()
    parser.add_section(section)
    for option, value in options.items():
        parser.set(section, option, value)
    return cls(name, parser, section, server)
コード例 #47
0
ファイル: AdvConfig.py プロジェクト: CarlEdman/MakeMP4
  def set(self,option,value=None,section=None):
    if not section:
      if not self.currentsection: raise configparser.NoSectionError('No Current Section Set')
      section=self.currentsection

    oval=RawConfigParser.get(self,section,option) if self.has_option(section,option) else None
    nval=self.valtostr(value)
    if oval and oval==nval: return
    RawConfigParser.set(self,section,option,nval)
    self.modified=True
コード例 #48
0
ファイル: config.py プロジェクト: fecori/Watson
    def set(self, section, option, value):
        """
        Set option in given configuration section to value.

        If section does not exist yet, it is added implicitly.

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

        RawConfigParser.set(self, section, option, value)
コード例 #49
0
ファイル: graphical.py プロジェクト: Darriall/pinguino-ide
    def save_raw_parser(self, content, filename):

        file_parser = RawConfigParser()
        count = 0
        for block in content:
            count += 1
            name_section = "Block-%d"%count
            file_parser.add_section(name_section)
            for key in block.keys():
                file_parser.set(name_section, key, block[key])
        file_parser.write(codecs.open(filename, "w", "utf-8"))
コード例 #50
0
ファイル: config.py プロジェクト: labedz/poezio
 def set_and_save(self, option, value, section=DEFSECTION):
     """
     set the value in the configuration then save it
     to the file
     """
     if self.has_section(section):
         RawConfigParser.set(self, section, option, value)
     else:
         self.add_section(section)
         RawConfigParser.set(self, section, option, value)
     self.write_in_file(section, option, value)
コード例 #51
0
 def setConfigContent(self, content):
     conf = RawConfigParser()
     conf_file = open(self.file_path, 'w')
     conf_file.write('')
     conf.read(self.file_path)
     for section in content:
         section_items = content[section].items()
         for option, value in section_items:
             if conf.has_section(section) == False:
                 conf.add_section(section)
             conf.set(section, option, value)
     conf.write(open(self.file_path, "w"))
コード例 #52
0
ファイル: plugins_script_test.py プロジェクト: gryphius/fuglu
    def setUp(self):
        try:
            from configparser import RawConfigParser
        except ImportError:
            from ConfigParser import RawConfigParser
        config = RawConfigParser()

        config.add_section('ScriptFilter')
        config.set('ScriptFilter', 'scriptdir', os.path.abspath(
            os.path.dirname(__file__) + '/testdata/scriptfilter'))

        self.candidate = ScriptFilter(config)
コード例 #53
0
ファイル: config.py プロジェクト: ripperbone/turses
    def generate_token_file(self, token_file, oauth_token, oauth_token_secret):
        self.oauth_token = oauth_token
        self.oauth_token_secret = oauth_token_secret

        conf = RawConfigParser()
        conf.add_section(SECTION_TOKEN)
        conf.set(SECTION_TOKEN, "oauth_token", oauth_token)
        conf.set(SECTION_TOKEN, "oauth_token_secret", oauth_token_secret)

        with open(token_file, "w") as tokens:
            conf.write(tokens)

        print(encode(_("your account has been saved")))
コード例 #54
0
ファイル: acbs_parser.py プロジェクト: liushuyu/DraftBin
def write_acbs_conf():
    acbs_conf_writer = RawConfigParser()
    acbs_conf_writer.add_section('default')
    acbs_conf_writer.set('default', 'location', '/var/lib/abbs/repo/')
    acbs_conf_writer.add_section('acbs')
    acbs_conf_writer.set('acbs', 'location', '/var/lib/acbs/repo/')
    try:
        fp = open('/etc/acbs_forest.conf', 'w')
        acbs_conf_writer.write(fp)
    except:
        err_msg('Unable to write initial configuration file!')
        return False
    return True
コード例 #55
0
ファイル: config.py プロジェクト: kookerus/UnitsConverter
 def create_default(self):
     """
         Create a default settings file
     """
     config = RawConfigParser()
     configfile = open(self.file_name, "w")
     config.add_section('Settings')
     config.set('Settings', 'dark_mode', "0")
     config.add_section('Plugins')
     available_plugins = ",".join(self.get_available_plugins())
     config.set('Plugins', 'active_plugins', available_plugins)
     config.write(configfile)
     configfile.close()
コード例 #56
0
ファイル: config.py プロジェクト: kookerus/UnitsConverter
 def set_property(self, section, property, value):
     """
         Change a property in settings ini file
     """
     config = RawConfigParser()
     config.read(self.file_name)
     if section in config.sections():
         config.set(section, property, str(value).strip())
         configfile = open(self.file_name , "w")
         config.write(configfile)
         configfile.close()
     else:
         print("Error, the settings file seem to be modified manualy")
コード例 #57
0
ファイル: update_conf.py プロジェクト: datapythonista/viri
    def run(self):
        try:
            config_file = DEFAULT_CONF_FILE
            if not os.path.isfile(config_file):
                raise ValueError('Configuration file not found: {0}'.format(config_file))
        
            config = RawConfigParser()
            config.read(config_file)

            if 'security' in config.sections():
                return 'The configuration file is already migrated to the new version'

            config.add_section('security')
            config.add_section('database')

            for item in config.items('paths'):
                if item[0] == 'database_file':
                    config.set('database', item[0], item[1])
                else:
                    config.set('security', item[0], item[1])
            
            config.remove_section('paths')

            config.set('security', 'crl_file_url', 'None')            
            config.set('logging', 'log_level', 'INFO')
        
            with open(config_file, 'w') as file:
                config.write(file)

        except Exception as exc:
            return exc

        return 'Configuration file migrated'