簡體   English   中英

將 tqdm 進度條與 asyncio 一起使用

[英]Use tqdm progress bar with asyncio

我正在嘗試創建一個進度條,只要異步任務完成,該進度條就會更新。

我有以下代碼

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])

感謝您的幫助,使其與單個動態進度條一起工作

如果在創建並發任務后在run_scan掃描方法中調用self.pbar.update(1) ,每個任務都會為自己更新pbar 所以你的班級應該如下所示

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM