当前位置: 首页>>代码示例>>Python>>正文


Python six.iterkeys函数代码示例

本文整理汇总了Python中salt.ext.six.iterkeys函数的典型用法代码示例。如果您正苦于以下问题:Python iterkeys函数的具体用法?Python iterkeys怎么用?Python iterkeys使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了iterkeys函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: render

def render(jp_data, saltenv='base', sls='', **kws):
    '''
    Accepts Java Properties as a string or as a file object and runs it through the jproperties
    parser. Uses the jproperties package https://pypi.python.org/pypi/jproperties so please
    "pip install jproperties" to use this renderer.

    Returns a flat dictionary by default:
      {'some.java.thing': 'whatever'}
    If using a 'shebang' "#!jproperties" header on the first line, an argument can be optionally
    supplied as a key to contain a dictionary of the rendered properties (ie. "#!jproperties foo"):
      {'foo': {'some.java.thing': 'whatever'}}

    :rtype: A Python data structure
    '''
    if not isinstance(jp_data, string_types):
        jp_data = jp_data.read()

    container = False
    if jp_data.startswith('#!'):
        args = jp_data[:jp_data.find('\n')].split()
        if len(args) >= 2:
            container = args[1]
        jp_data = jp_data[(jp_data.find('\n') + 1):]
    if not jp_data.strip():
        return {}
    properties = jp()
    properties.load(jp_data)
    if container:
        return {container: dict([(k, properties[k]) for k in six.iterkeys(properties)])}
    else:
        return dict([(k, properties[k]) for k in six.iterkeys(properties)])
开发者ID:beornf,项目名称:salt-contrib,代码行数:31,代码来源:jproperties.py

示例2: test_kill

    def test_kill(self):
        def spin():
            salt.utils.appendproctitle('test_kill')
            while True:
                time.sleep(1)

        process_manager = salt.utils.process.ProcessManager()
        process_manager.add_process(spin)
        initial_pid = next(six.iterkeys(process_manager._process_map))
        # kill the child
        os.kill(initial_pid, signal.SIGKILL)
        # give the OS time to give the signal...
        time.sleep(0.1)
        process_manager.check_children()
        try:
            assert initial_pid != next(six.iterkeys(process_manager._process_map))
        finally:
            process_manager.stop_restarting()
            process_manager.kill_children()
            time.sleep(0.5)
            # Are there child processes still running?
            if process_manager._process_map.keys():
                process_manager.send_signal_to_processes(signal.SIGKILL)
                process_manager.stop_restarting()
                process_manager.kill_children()
开发者ID:bryson,项目名称:salt,代码行数:25,代码来源:process_test.py

示例3: __call_cli

def __call_cli(jboss_config, command, retries=1):
    command_segments = [
        jboss_config['cli_path'],
        '--connect',
        '--controller="{0}"'.format(jboss_config['controller'])
    ]
    if 'cli_user' in six.iterkeys(jboss_config):
        command_segments.append('--user="{0}"'.format(jboss_config['cli_user']))
    if 'cli_password' in six.iterkeys(jboss_config):
        command_segments.append('--password="{0}"'.format(jboss_config['cli_password']))
    command_segments.append('--command="{0}"'.format(__escape_command(command)))
    cli_script = ' '.join(command_segments)

    cli_command_result = __salt__['cmd.run_all'](cli_script)
    log.debug('cli_command_result=%s', str(cli_command_result))

    log.debug('========= STDOUT:\n%s', cli_command_result['stdout'])
    log.debug('========= STDERR:\n%s', cli_command_result['stderr'])
    log.debug('========= RETCODE: %d', cli_command_result['retcode'])

    if cli_command_result['retcode'] == 127:
        raise CommandExecutionError('Could not execute jboss-cli.sh script. Have you specified server_dir variable correctly?\nCurrent CLI path: {cli_path}. '.format(cli_path=jboss_config['cli_path']))

    if cli_command_result['retcode'] == 1 and 'Unable to authenticate against controller' in cli_command_result['stderr']:
        raise CommandExecutionError('Could not authenticate against controller, please check username and password for the management console. Err code: {retcode}, stdout: {stdout}, stderr: {stderr}'.format(**cli_command_result))

    # It may happen that eventhough server is up it may not respond to the call
    if cli_command_result['retcode'] == 1 and 'JBAS012144' in cli_command_result['stderr'] and retries > 0:  # Cannot connect to cli
        log.debug('Command failed, retrying... (%d tries left)', retries)
        time.sleep(3)
        return __call_cli(jboss_config, command, retries - 1)

    return cli_command_result
开发者ID:DaveQB,项目名称:salt,代码行数:33,代码来源:jboss7_cli.py

示例4: table_find

def table_find(table_to_find):
    '''
    Finds the schema in which the
    given table is present

    CLI Example::

        salt '*' drizzle.table_find table_name
    '''

    # Initializing the required variables
    ret_val = {}
    count = 1
    drizzle_db = _connect()
    cursor = drizzle_db.cursor()

    # Finding the schema
    schema = schemas()
    for schema_iter in six.iterkeys(schema):
        table = tables(schema[schema_iter])
        for table_iter in six.iterkeys(table):
            if table[table_iter] == table_to_find:
                ret_val[count] = schema[schema_iter]
                count = count+1

    cursor.close()
    drizzle_db.close()
    return ret_val
开发者ID:beornf,项目名称:salt-contrib,代码行数:28,代码来源:drizzle.py

示例5: SetIncludes

 def SetIncludes(self, includes):
     if includes:
         for inc in includes:
             value = inc[next(six.iterkeys(inc))]
             include = next(six.iterkeys(inc))
             self.SetInclude(include, value)
             log.debug('was asked to set {0} to {1}'.format(include, value))
开发者ID:DaveQB,项目名称:salt,代码行数:7,代码来源:win_update.py

示例6: test_cmd_call

    def test_cmd_call(self):
        result = self.HIGHSTATE.state.call_template_str(
            textwrap.dedent(
                """\
            #!pydsl
            state('A').cmd.run('echo this is state A', cwd='/')

            some_var = 12345
            def do_something(a, b, *args, **kws):
                return dict(result=True, changes={'a': a, 'b': b, 'args': args, 'kws': kws, 'some_var': some_var})

            state('C').cmd.call(do_something, 1, 2, 3, x=1, y=2) \
                          .require(state('A').cmd)

            state('G').cmd.wait('echo this is state G', cwd='/') \
                          .watch(state('C').cmd)
        """
            )
        )
        ret = next(result[k] for k in six.iterkeys(result) if "do_something" in k)
        changes = ret["changes"]
        self.assertEqual(changes, dict(a=1, b=2, args=(3,), kws=dict(x=1, y=2), some_var=12345))

        ret = next(result[k] for k in six.iterkeys(result) if "-G_" in k)
        self.assertEqual(ret["changes"]["stdout"], "this is state G")
开发者ID:bryson,项目名称:salt,代码行数:25,代码来源:pydsl_test.py

示例7: list_upgrades

def list_upgrades(jid, style="group", outputter="nested", ext_source=None):
    """
    Show list of available pkg upgrades using a specified format style

    CLI Example:

    .. code-block:: bash

        salt-run pkg.list_upgrades jid=20141120114114417719 style=group
    """
    mminion = salt.minion.MasterMinion(__opts__)
    returner = _get_returner((__opts__["ext_job_cache"], ext_source, __opts__["master_job_cache"]))

    data = mminion.returners["{0}.get_jid".format(returner)](jid)
    pkgs = {}

    if style == "group":
        for minion in data:
            results = data[minion]["return"]
            for pkg, pkgver in six.iteritems(results):
                if pkg not in six.iterkeys(pkgs):
                    pkgs[pkg] = {pkgver: {"hosts": []}}

                if pkgver not in six.iterkeys(pkgs[pkg]):
                    pkgs[pkg].update({pkgver: {"hosts": []}})

                pkgs[pkg][pkgver]["hosts"].append(minion)

    if outputter:
        salt.output.display_output(pkgs, outputter, opts=__opts__)

    return pkgs
开发者ID:bryson,项目名称:salt,代码行数:32,代码来源:pkg.py

示例8: stages_iter

    def stages_iter(self):
        '''
        Return an iterator that yields the state call data as it is processed
        '''

        def yielder(gen_ret):
            if (not isinstance(gen_ret, list)
                    and not isinstance(gen_ret, dict)
                    and hasattr(gen_ret, 'next')):
                for sub_ret in gen_ret:
                    for yret in yielder(sub_ret):
                        yield yret
            else:
                yield gen_ret

        self.over_run = {}
        yield self.over
        for comp in self.over:
            name = next(six.iterkeys(comp))
            stage = comp[name]
            if name not in self.over_run:
                v_stage = self.verify_stage(stage)
                if isinstance(v_stage, list):
                    yield [comp]
                    yield v_stage
                else:
                    for sret in self.call_stage(name, stage):
                        for yret in yielder(sret):
                            sname = next(six.iterkeys(yret))
                            yield [self.get_stage(sname)]
                            final = {}
                            for minion in yret[sname]:
                                final[minion] = yret[sname][minion]['ret']
                            yield final
开发者ID:dmyerscough,项目名称:salt,代码行数:34,代码来源:overstate.py

示例9: test_basic

    def test_basic(self):
        '''
        Make sure that the process is alive 2s later
        '''
        def spin():
            salt.utils.appendproctitle('test_basic')
            while True:
                time.sleep(1)

        process_manager = salt.utils.process.ProcessManager()
        process_manager.add_process(spin)
        initial_pid = next(six.iterkeys(process_manager._process_map))
        time.sleep(2)
        process_manager.check_children()
        try:
            assert initial_pid == next(six.iterkeys(process_manager._process_map))
        finally:
            process_manager.stop_restarting()
            process_manager.kill_children()
            time.sleep(0.5)
            # Are there child processes still running?
            if process_manager._process_map.keys():
                process_manager.send_signal_to_processes(signal.SIGKILL)
                process_manager.stop_restarting()
                process_manager.kill_children()
开发者ID:bryson,项目名称:salt,代码行数:25,代码来源:process_test.py

示例10: user_role_add

def user_role_add(user_id=None, user=None, tenant_id=None,
                  tenant=None, role_id=None, role=None, profile=None,
                  project_id=None, project_name=None, **connection_args):
    '''
    Add role for user in tenant (keystone user-role-add)

    CLI Examples:

    .. code-block:: bash

        salt '*' keystone.user_role_add \
user_id=298ce377245c4ec9b70e1c639c89e654 \
tenant_id=7167a092ece84bae8cead4bf9d15bb3b \
role_id=ce377245c4ec9b70e1c639c89e8cead4
        salt '*' keystone.user_role_add user=admin tenant=admin role=admin
    '''
    kstone = auth(profile, **connection_args)

    if project_id and not tenant_id:
        tenant_id = project_id
    elif project_name and not tenant:
        tenant = project_name

    if user:
        user_id = user_get(name=user, profile=profile,
                           **connection_args)[user].get('id')
    else:
        user = next(six.iterkeys(user_get(user_id, profile=profile,
                                          **connection_args)))['name']
    if not user_id:
        return {'Error': 'Unable to resolve user id'}

    if tenant:
        tenant_id = tenant_get(name=tenant, profile=profile,
                               **connection_args)[tenant].get('id')
    else:
        tenant = next(six.iterkeys(tenant_get(tenant_id, profile=profile,
                                              **connection_args)))['name']
    if not tenant_id:
        return {'Error': 'Unable to resolve tenant/project id'}

    if role:
        role_id = role_get(name=role, profile=profile,
                           **connection_args)[role]['id']
    else:
        role = next(six.iterkeys(role_get(role_id, profile=profile,
                                          **connection_args)))['name']
    if not role_id:
        return {'Error': 'Unable to resolve role id'}

    if _OS_IDENTITY_API_VERSION > 2:
        kstone.roles.grant(role_id, user=user_id, project=tenant_id)
    else:
        kstone.roles.add_user_role(user_id, role_id, tenant_id)
    ret_msg = '"{0}" role added for user "{1}" for "{2}" tenant/project'
    return ret_msg.format(role, user, tenant)
开发者ID:bryson,项目名称:salt,代码行数:56,代码来源:keystone.py

示例11: test_restarting

    def test_restarting(self):
        '''
        Make sure that the process is alive 2s later
        '''
        def die():
            time.sleep(1)

        process_manager = salt.utils.process.ProcessManager()
        process_manager.add_process(die)
        initial_pid = next(six.iterkeys(process_manager._process_map))
        time.sleep(2)
        process_manager.check_children()
        assert initial_pid != next(six.iterkeys(process_manager._process_map))
        process_manager.kill_children()
开发者ID:DaveQB,项目名称:salt,代码行数:14,代码来源:process_test.py

示例12: test_kill

    def test_kill(self):
        def spin():
            while True:
                time.sleep(1)

        process_manager = salt.utils.process.ProcessManager()
        process_manager.add_process(spin)
        initial_pid = next(six.iterkeys(process_manager._process_map))
        # kill the child
        os.kill(initial_pid, signal.SIGTERM)
        # give the OS time to give the signal...
        time.sleep(0.1)
        process_manager.check_children()
        assert initial_pid != next(six.iterkeys(process_manager._process_map))
        process_manager.kill_children()
开发者ID:DaveQB,项目名称:salt,代码行数:15,代码来源:process_test.py

示例13: test_basic

    def test_basic(self):
        '''
        Make sure that the process is alive 2s later
        '''
        def spin():
            while True:
                time.sleep(1)

        process_manager = salt.utils.process.ProcessManager()
        process_manager.add_process(spin)
        initial_pid = next(six.iterkeys(process_manager._process_map))
        time.sleep(2)
        process_manager.check_children()
        assert initial_pid == next(six.iterkeys(process_manager._process_map))
        process_manager.kill_children()
开发者ID:DaveQB,项目名称:salt,代码行数:15,代码来源:process_test.py

示例14: purge

def purge(name, delete_key=True):
    '''
    Destroy the named vm
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    data = vm_info(name, quiet=True)
    if not data:
        __jid_event__.fire_event({'error': 'Failed to find vm {0} to purge'.format(name)}, 'progress')
        return 'fail'
    hyper = next(six.iterkeys(data))
    try:
        cmd_ret = client.cmd_iter(
                hyper,
                'virt.purge',
                [name, True],
                timeout=600)
    except SaltClientError as client_error:
        return 'Virtual machine {0} could not be purged: {1}'.format(name, client_error)

    for comp in cmd_ret:
        ret.update(comp)

    if delete_key:
        skey = salt.key.Key(__opts__)
        skey.delete_key(name)
    __jid_event__.fire_event({'message': 'Purged VM {0}'.format(name)}, 'progress')
    return 'good'
开发者ID:DaveQB,项目名称:salt,代码行数:28,代码来源:virt.py

示例15: force_off

def force_off(name):
    '''
    Force power down the named virtual machine
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    data = vm_info(name, quiet=True)
    if not data:
        print('Failed to find vm {0} to destroy'.format(name))
        return 'fail'
    hyper = next(six.iterkeys(data))
    if data[hyper][name]['state'] == 'shutdown':
        print('VM {0} is already shutdown'.format(name))
        return'bad state'
    try:
        cmd_ret = client.cmd_iter(
                hyper,
                'virt.destroy',
                [name],
                timeout=600)
    except SaltClientError as client_error:
        return 'Virtual machine {0} could not be forced off: {1}'.format(name, client_error)
    for comp in cmd_ret:
        ret.update(comp)
    __jid_event__.fire_event({'message': 'Powered off VM {0}'.format(name)}, 'progress')
    return 'good'
开发者ID:DaveQB,项目名称:salt,代码行数:26,代码来源:virt.py


注:本文中的salt.ext.six.iterkeys函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。