网络自动化(5):concurrent.futures的线程池方法使用

首先看如下代码:

其中read_cmdb()为自定义的函数,实现对表格数据清洗,asset_check()为自定义函数,实现对多型号设备远程登录管理,并发送命令,提取出想要的信息并返回;

from concurrent.futures.thread import ThreadPoolExecutor
from concurrent.futures._base import as_completed


def receive_info():
    executor = ThreadPoolExecutor(max_workers=10)
    ips = read_cmdb()
    # print(json.dumps(ips,indent=4))
    tasks = []
    all_result = []
    for host_info in ips:
        ip = host_info['host']
        username = host_info['username']
        password = host_info['password']
        device_type = host_info['device_type']
        equipment_model = host_info['equipment_model']
        sn = host_info['sn']
        asset = host_info['asset']
        task = executor.submit(asset_check, ip, username, password, device_type, equipment_model, sn, asset)   #调用任务对象
from concurrent.futures.thread import ThreadPoolExecutor
ThreadPoolExecutor
为线程生成器,可以添加任务,可以通过”max_workers“参数来控制线程池的大小(任务数多少);
from concurrent.futures._base import as_completed
as_completed通过动态调度已添加的任务,返回任务结果,从而减少阻塞时间;

”“”
此处可以直接采用result方法获取任务的值(可见我的另一篇笔记:

网络自动化之pyton(4):paramiko+concurrent.futures多线程测试,将获取的设备SN等信息添加到CSV表中

直接获取结果,能更清晰的观察自定义远程函数asset_check()的执行结果,相当于单线程,可以在测试时使用,连链接中的笔记未指出后文提到的阻塞情况,在此处补充

),但是result()会导致线程阻塞直至该任务完成,如需真正实现多线程,正确的方法是,将多个‘asset_check()’对象加入到池子中,然后通过as_completed()去获取众多任务对象的值,由于任务对象在列表中是独立存在的,即有独立的索引,因此众多对象的值亦是如此,可以通过索引、遍历等方法取出
“”“


见如下部分代码:

        tasks.append(task) #将任务调价到字典中
        print("all_task size is " + str(len(tasks)))
    for future in as_completed(tasks):
        result = future.result()
        all_result.append(result)
        return all_result

 

posted @ 2022-04-15 14:42  段愿仁长九  阅读(237)  评论(0)    收藏  举报