[Python]asyncio异步协程停止问题

python版本:3.9
做异步协程停止时,调用asyncio.Task.all_task时会报一个
AttributeError: type object '_asyncio.Task' has no attribute 'all_tasks'的错误
然后查了一下,说是3.9中把asyncio.Task.all_tasks移除了,用asyncio.all_tasks代替
代替后会报
RuntimeError: no running event loop的错误

以下是代码:

import time, asyncio


async def do_work(s):
    print('waiting:', s)
    await asyncio.sleep(s)
    return 'Done after {}s'.format(s)


# 创建协程对象
coroutine1 = do_work(1)
coroutine2 = do_work(2)
coroutine3 = do_work(4)

# 创建任务列表
tasks = [asyncio.ensure_future(coroutine1),
         asyncio.ensure_future(coroutine2),
         asyncio.ensure_future(coroutine3)]

start = time.time()
loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(asyncio.wait(tasks))
except KeyboardInterrupt as e:
    # 获取事件循环中所有任务列表
    print(asyncio.all_tasks)
    for task in asyncio.all_tasks():
        print(task.cancel())    # 如果返回的True代表当前任务取消成功
    loop.stop()
    loop.run_forever()
finally:
    loop.close()
print('Time:', time.time()-start)

RuntimeError: no running event loop的错误 没有在运行的事件循环 应该是这里的问题吧,loop = asyncio.get_event_loop()

补充:这段代码在终端terminal中运行

all_tasks到底是属性还是函数,你一会有括号一会没有括号的能对才怪