python3.9 all_tasks()问题
来源:13-3 task取消和子协程调用原理
Necromancer_
2022-01-02
python3.9中 asyncio.Task.all_tasks()调用变为了asyncio.all_tasks(),但是有一个问题,在捕获KeyboardInterrupt后all_tasks = asyncio.all_tasks()无法找到当前事件循环,报错no running event loop,需要在all_tasks = asyncio.all_tasks(loop)中直接传入loop,传入参数loop后代码正常运行。查阅官方文档与谷歌搜索后无法理解为何all_tasks(None)无法找到当前event loop,遂请教老师!
# -*- coding: utf-8 -*-
import asyncio
import time
async def get(time):
print('waiting')
await asyncio.sleep(time)
print(f'down after {time}s')
if __name__ == '__main__':
starttime = time.time()
task1 = get(2)
task2 = get(3)
task3 = get(3)
tasks = [task1,task2,task3]
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(asyncio.wait(tasks))
except KeyboardInterrupt as e:
alltasks = asyncio.all_tasks(loop)
for task in alltasks:
print('cancel')
print(task.cancel())
loop.stop()
loop.run_forever()
finally:
loop.close()
print(time.time()-starttime)写回答
1回答
-
Necromancer_
提问者
2022-01-03
老师你好,问题已找到答案。通过查阅python3.6与python3.9的asyncio源码发现问题是调用方法get_event_loop()与get_running_loop()的不同,python3.6中使用get_event_loop(),而3.9的asyncio.all_tasks()是调用了get_running_loop(),而二者的区别答案链接如下:https://stackoverflow.com/questions/65206110/when-should-we-use-asyncio-get-running-loop-vs-asyncio-get-event-loop
012022-01-04
相似问题