我正在嘗試創建一個進度條,只要異步任務完成,該進度條就會更新。
我有以下代碼
scan_results = []
tasks = [self.run_scan(i) for i in input_paths]
pbar = tqdm(total=len(tasks), desc='Scanning files')
for f in asyncio.as_completed(tasks):
value = await f
pbar.update(1)
scan_results.append(value)
上面的代碼生成一個進度條,但直到所有任務完成后才會更新(當有多個任務時,它顯示 0% 或 100%)
我也嘗試過使用tqdm.asyncio.tqdm.gather
with tqdm(total=len(input_paths)):
scan_results = await tqdm.gather(*[self.run_scan(i) for i in input_paths])
上面的代碼生成多個進度條,和前面的代碼塊一樣,它顯示 0% 或 100%
我的出發點是
scan_results = await asyncio.gather(*[self.run_scan(i)for i in input_paths])
感謝您的幫助,使其與單個動態進度條一起作業
uj5u.com熱心網友回復:
如果你在創建并發任務后self.pbar.update(1)在scan方法內部呼叫run_scan,每個任務都會更新pbarfor self。所以你的班級應該如下所示
class Cls:
async def run_scan(self, path):
...
self.pbar.update(1)
def scan(self, input_paths):
loop = asyncio.get_event_loop()
tasks = [loop.create_task(self.run_scan(i)) for i in input_paths]
self.pbar = tqdm(total=len(input_paths), desc='Scanning files')
loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/492219.html
標籤:Python python-3.x 进度条 蟒蛇异步 tqdm
