在ThreadPoolexecutor进程中使用concurrent.futures创建进度条

1 python multithreading python-multithreading python-3.x progress-bar

我有一个 python 脚本,它连接到多个远程主机并执行 Linux 命令来获取信息。今天的主机数量约为 400 台主机,在这种情况下,我使用 aThreadPoolExecutor来在尽可能短的时间内完成所有任务。

一切顺利,我在 100 秒左右获得了所有数据。问题是我不知道这段时间进程的状态是什么,我想添加一个进度条,当所有的Threads完成时结束。

在我这边,我添加了新代码,使这个进度条成为我的脚本,使用睡眠时间,但正如我所看到的,进度条与线程进程不同步(进度条在线程进程之前几秒钟结束)。

对此有更好的解决方案吗?当这一切运行良好时,我想将这个进度条迁移到 Django 网站中。

这里有我的代码脚本的一部分。

for host in lista_hosts:
        res_versiones[host] = val_defecto
    # print(res_versiones)     
    
LENGTH = len(lista_hosts) # Number of iterations required to fill pbar 
pbar = tqdm(total=LENGTH, desc='consulta_comando') # Init pbar
    
    with ThreadPoolExecutor(200) as executor:    
    
        for host in lista_hosts:
            host_dns = add_dns_cc.add_dns_concesion(host)
         
            res_command_remote = executor.submit(comando_remoto.comando_remoto_hosts, host_dns, comando, res_versiones, user, clave_rsa, passwd)
            
            time.sleep(0.2)
            pbar.update(n=1) # Increments counter
        end = time.time() print(f"Runtime of the program is {end - start}")
Run Code Online (Sandbox Code Playgroud)

小智 7

每次将作业提交到 时,您的代码都会更新进度条Executor,但您应该在每次作业完成时更新它。

您可以将返回的期货保留submit在列表中并使用以下命令检查是否完成as_completed

from concurrent.futures import ThreadPoolExecutor, as_completed

#   ... snip.....

LENGTH = len(lista_hosts)  # Number of iterations required to fill pbar
pbar = tqdm(total=LENGTH, desc='consulta_comando')  # Init pbar
with ThreadPoolExecutor(200) as executor:
    futures = [executor.submit(comando_remoto.comando_remoto_hosts,
                               add_dns_cc.add_dns_concesion(host),
                               comando, res_versiones, user, clave_rsa,
                               passwd) for host in lista_hosts]
    for _ in as_completed(futures):
        pbar.update(n=1)  # Increments counter
Run Code Online (Sandbox Code Playgroud)