每个进程池工作进程进度条的TQM

2024-09-23 22:22:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图实现的任务是在多核机器上处理数千个不同大小的工件。我希望使用process pool executor分发作业,并让每个工作人员告诉我它正在处理哪个文件

到目前为止,我有以下几点:

from concurrent.futures import ProcessPoolExecutor

from itertools import islice, cycle

import time
import tqdm
import multiprocessing
import random

worker_count = min(multiprocessing.cpu_count(), 10)
flist=range(100)
executor = ProcessPoolExecutor(max_workers=worker_count)

with tqdm.tqdm(total=len(flist), leave=False) as t:
    t.set_description_str("Extracting ... ")
    pbars = []

    for idx in range(t.pos + 1, t.pos + 1 + worker_count):
        pbars.append(tqdm.tqdm(position=idx, bar_format='{desc}', leave=False))

    def process(entry):
        artifact, idx = entry
        time.sleep(random.randint(0, worker_count)/10.0)
        pbars[idx].set_description_str(f'Working on {artifact}', refresh=True)
        return artifact
    for _, _ in zip(flist, executor.map(process, zip(flist, islice(cycle(range(worker_count)), len(flist))))):
        t.update()

    for idx in range(worker_count):
        pbars[idx].set_description_str(" "*(pbars[idx].ncols - 1), refresh=True)
        pbars[idx].clear()
        pbars[idx].close()

Running demo

当然,我将显示文件名,而不是数字

现在,问题是:

  1. 有没有更好的方法来达到我想要的
  2. 关于清除PBAR的最后一点对我来说似乎很讨厌。我这样做基本上是为了在程序结束时清理终端。也许有更好的办法

Tags: inimportforcountrangedescriptionprocessworker