aiohttp/asyncio代码执行顺序不符合预期,如何调整让指定打印先于sleep执行?
问题原因
你现有代码的执行顺序不符合预期,核心是loop.run_until_complete(task)是阻塞方法,会一直等待传入的异步任务完全执行完成后才会返回,所以你写在它后面的print("In the process of accessing web")自然要等2秒sleep结束后才会执行。
调整方案
只需要把要优先执行的打印语句挪到loop.run_until_complete之前即可,调整后的完整代码如下:
import asyncio import time import aiohttp now = lambda :time.time() async def do_some_work(x): print("waiting:",x) await asyncio.sleep(x) return f"Web is ok" start = now() coroutine = do_some_work(2) loop = asyncio.get_event_loop() task = asyncio.ensure_future(coroutine) # 先执行要优先打印的语句 print("In the process of accessing web") loop.run_until_complete(task) print("Task ret:", task.result()) print("Time:", now() - start)
调整后的执行顺序
- 执行
python3 test_aio_return.py启动程序 - 打印
In the process of accessing web - 打印
waiting: 2,进入2秒sleep阻塞 - 打印
Task ret: Web is ok - 程序总耗时约2秒,完全符合预期。
如果你的运行环境是Python 3.7及以上版本,也可以用更简洁的asyncio.run写法,不需要手动管理事件循环:
import asyncio import time import aiohttp now = lambda :time.time() async def do_some_work(x): print("waiting:",x) await asyncio.sleep(x) return f"Web is ok" async def main(): task = asyncio.create_task(do_some_work(2)) print("In the process of accessing web") res = await task print("Task ret:", res) start = now() asyncio.run(main()) print("Time:", now() - start)
内容的提问来源于stack exchange,提问作者NewOne
相关产品推荐
相关产品推荐

