如何找出事件循环中有多少活动任务? 在文档中我只找到asyncio.Task.all_tasks()但它是简单的增量计数器:
import asyncio
async def coro():
await asyncio.sleep(1)
async def main():
tasks = []
print('Tasks count: ', len(asyncio.Task.all_tasks()))
for idx in range(3):
task = asyncio.ensure_future(coro())
tasks.append(task)
print('Tasks count: ', len(asyncio.Task.all_tasks()))
await asyncio.gather(*tasks)
print('Tasks count: ', len(asyncio.Task.all_tasks()))
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
输出:
Tasks count: 1
Tasks count: 2
Tasks count: 3
Tasks count: 4
Tasks count: 4
预期产出:
Tasks count: 1
Tasks count: 2
Tasks count: 3
Tasks count: 4
Tasks count: 1
答案 0 :(得分:6)
all_tasks
返回所有已注册的任务,包括已完成的任务。您只需按done()
过滤任务即可获得有效任务:
import asyncio
async def coro():
await asyncio.sleep(1)
async def main():
tasks = []
print('Tasks count: ', len(asyncio.Task.all_tasks()))
for idx in range(3):
task = asyncio.ensure_future(coro())
tasks.append(task)
print('Tasks count: ', len(asyncio.Task.all_tasks()))
await asyncio.gather(*tasks)
print('Tasks count: ', len(asyncio.Task.all_tasks()))
print('Active tasks count: ', len(
[task for task in asyncio.Task.all_tasks() if not task.done()])
)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
哪个输出:
Tasks count: 1
Tasks count: 2
Tasks count: 3
Tasks count: 4
Tasks count: 4
Active tasks count: 1
答案 1 :(得分:2)
在Python 3.7+中,有一个asyncio.all_tasks()
方法返回当前正在运行的循环中未完成的任务。
因此,它简化为:
count_active_tasks = len(asyncio.all_tasks())