我想在每个python进程中使用4个python进程和tqdm进度条:
66%|███████████████████████████▌ | 80/122 [00:44<00:23, 1.79it/s]
35%|██████████████▉ | 18/52 [00:08<00:16, 2.01it/s]
26%|█████████▋ | 61/108 [00:44<00:34, 1.38it/s]
56%|███████████████████████▋ | 61/108 [00:44<00:34, 1.38it/s]
,所以他们都显示和更新像一个在同一时间。我该怎么做呢?
import multiprocessing
import random
import time
import tqdm
def task(position, lock):
total_iterations = 5
with lock:
bar = tqdm.tqdm(
desc=f'Position {position}',
total=total_iterations,
position=position,
leave=False
)
for _ in range(total_iterations):
time.sleep(random.uniform(0.5, 1))
with lock:
bar.update(1)
with lock:
bar.close()
if __name__ == '__main__':
lock = multiprocessing.Manager().Lock()
with multiprocessing.Pool(4) as pool:
for position in range(4):
pool.apply_async(task, args = (position + 1, lock))
pool.close()
pool.join()
- 使用
tqdm
的位置标志(如评论中建议的),我设置行号以打印每个栏。 - 我使用
Lock
实例来防止多个进程同时写入标准输出。