python - 将 tqdm 进度条与 asyncio 结合使用

标签 python python-3.x progress-bar python-asyncio tqdm

我正在尝试创建一个进度条,每当异步任务完成时都会更新该进度条。

我有以下代码

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

关于python - 将 tqdm 进度条与 asyncio 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72645095/

相关文章:

python - 有没有办法计算 Spark df 中每行的非空值?

python - 您能解释一下具有 BatchNormalization 的神经网络中的 Keras get_weights() 函数吗?

user-interface - 我如何添加或导入 pyqt 和 sip 到 Python

python - 无法解析 h4 标签内的数据 : Python3

android - 进度条 % 已完成(下载)在 Android 中显示

python - 在 linux 上将 web.py 作为服务运行

python - ImportError:/home/test/test_1.so: 来自 cython 构建的错误 ELF 类

Python:如何从字符串中删除数字周围的引号

javascript - 如何使用 javascript 将属性从设置属性转换为新属性

Javascript 变量未解析,显示为空白或 null