python - 如何使用 Fabric 使其并行运行?

标签 python parallel-processing fabric

我之前问过一个相关问题:

How to issue commands on remote hosts in parallel using Fabric without using a fabfile?

我在各种测试主机上并行执行测试时遇到问题。

我的代码如下所示:

@parallel  
def run_test(arg_list):
    # arg_list is a list of dictionary.  Each entry in
    # arg_list has a 'ip_address' and a 'test_config_file'

    for x in arg_list:
        ip_address = x['ip_address']
        test_config_file = x['test_config_file']
        env['host_string'] = ip_address
        # The test program "test_localhost.py" is already on all the Test hosts
        cmd = "/root/test_localhost.py --ip_addr=" + ip_address + " --config=" + test_config_file
        run(cmd)


if __name__ == '__main__':

    env.parallel = True

    # Each test host will have unique test_config_files
    arg_list = list()
    arg_list.append({'ip_address':'10.10.10.10', 'test_config_file': "config_01.json"})
    arg_list.append({'ip_address':'10.10.10.11', 'test_config_file': "config_02.json"})

    execute(run_test, arg_list)

我已经针对 2 个以上的测试主机运行了此代码。我有一个脚本来检查测试是否正在测试主机上运行。这些测试不是并行运行的。

相反,测试是按顺序运行的 - “test_localhost.py”首先在 10.10.10.10 上运行,然后在完成后在 10.10.10.11 上运行。

我还需要做些什么才能使测试并行运行吗?

注意:我无法使用 fabfile,因为我为每个测试主机发送不同的测试配置文件。

最佳答案

这就是我要做的。不同主机的不同参数的技巧是将信息添加到 env context_manager 中,以便您获取任务的特定于主机的参数。只需确保主机与您用于字典的键匹配,并且并行命令可以正常工作。最后,fabric 中的任务通常通过 fab 命令运行。我从未使用 native python 脚本尝试过它,并且不确定其后果或是否需要进行任何特殊处理。 Fabric 项目的典型格式是在名为 fabfile.py 的文件中定义任务,并且可以使用 fab 运行这些任务。

在名为 fabfile.py 的文件中:

from fabric.decorators import task, parallel
from fabric.operations import run
from fabric.context_managers import env

@task
def run_test(arg_list):
    # arg_list is a list of dictionary.  Each entry in
    # arg_list has a 'ip_address' and a 'test_config_file'
    env.hosts = [ x['ip_address'] for x in arg_list ]
    env.host_data = dict()
    for x in arg_list:
        env.host_data[x['ip_address']] = x
    execute(run_command)

@parallel
def run_command():
    context = env.host_data[env.host]
    cmd = '/root/test_localhost.py --ip_addr=%(ip_address)s --config=%(test_config_file)s' % context
    run(cmd)

@task 
def run_my_test():
    arg_list.append({'ip_address':'10.10.10.10', 'test_config_file': "config_01.json"})
    arg_list.append({'ip_address':'10.10.10.11', 'test_config_file': "config_02.json"})
    run_test(arg_list)

从命令行运行:

fab run_my_test

关于python - 如何使用 Fabric 使其并行运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40121392/

相关文章:

Python-Fab 不从文件读取值

python - 如何动态导入模块并将其名称作为字符串?

python - 创建丢失的目录/文件结构 - Python

python - 将嵌套列表中的特定组件从字符串更改为浮点

python - Fabric 和 Sudo 作为另一个用户

python - 通过 os.system() 激活 virtualenv

Python正则表达式提取带有+符号的单词

c# - 并行图像处理伪影

java - 排序 50 000 000 个数字

c++ - 在多个节点上运行时 MPI_Reduce() 中的死锁