我正在尝试,asyncio.create_task()但我正在处理此错误:下面是一个例子:import asyncioimport timeasync def async_say(delay, msg): await asyncio.sleep(delay) print(msg)async def main(): task1 = asyncio.create_task(async_say(4, 'hello')) task2 = asyncio.create_task(async_say(6, 'world')) print(f"started at {time.strftime('%X')}") await task1 await task2 print(f"finished at {time.strftime('%X')}")loop = asyncio.get_event_loop()loop.run_until_complete(main())出去:AttributeError: module 'asyncio' has no attribute 'create_task'所以我尝试使用以下代码片段 ( .ensure_future()) ,没有任何问题:async def main(): task1 = asyncio.ensure_future(async_say(4, 'hello')) task2 = asyncio.ensure_future(async_say(6, 'world')) print(f"started at {time.strftime('%X')}") await task1 await task2 print(f"finished at {time.strftime('%X')}")loop = asyncio.get_event_loop()loop.run_until_complete(main())出去:started at 13:19:44helloworldfinished at 13:19:50怎么了?[注意]:蟒蛇 3.6Ubuntu 16.04[更新]:借用@ user4815162342 Answer,我的问题解决了:async def main(): loop = asyncio.get_event_loop() task1 = loop.create_task(async_say(4, 'hello')) task2 = loop.create_task(async_say(6, 'world')) print(f"started at {time.strftime('%X')}") await task1 await task2 print(f"finished at {time.strftime('%X')}")loop = asyncio.get_event_loop()loop.run_until_complete(main())
2 回答
狐的传说
TA贡献1804条经验 获得超3个赞
将create_task在Python 3.7中加入顶级功能,并且您使用Python 3.6。在 3.7 之前,create_task仅作为事件循环上的方法可用,因此您可以像这样调用它:
async def main():
loop = asyncio.get_event_loop()
task1 = loop.create_task(async_say(4, 'hello'))
task2 = loop.create_task(async_say(6, 'world'))
# ...
await task1
await task2
这适用于 3.6 和 3.7 以及早期版本。asyncio.ensure_future也可以工作,但是当你知道你正在处理一个协程时,create_task更明确并且是首选选项。
添加回答
举报
0/150
提交
取消