在不关闭循环的情况下清除中断的事件循环

Clear an interrupted event loop without closing the loop

试试下面的代码:

import asyncio

async def fun1():
    #block
    await asyncio.sleep(10)

loop = asyncio.get_event_loop()
count = 0
while count < 10:
    count += 1
    print(count)
    try:
        fut = asyncio.ensure_future(asyncio.wait_for(fun1(),1))
        loop.run_until_complete(fut)
    except:
        pass

然后 asyncio.Task.all_tasks(loop=loop) 检查任务。您会看到所有 canceled/finished 任务仍然绑定到循环中。我怎样才能保持循环并只清除 finished/canceled 任务,而不是关闭并获得一个新循环?

任务将与 weakref 循环,这意味着如果不存在对它们的引用,它们将在下一次 gc 运行 中被垃圾回收:

import asyncio
import gc


def main():
    #  your code here
main()


print('Before gc:', asyncio.Task.all_tasks())

gc.collect()

print('After gc:', asyncio.Task.all_tasks())

gc 运行.

后你会看到空集