You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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)

调整后的执行顺序

  1. 执行python3 test_aio_return.py启动程序
  2. 打印In the process of accessing web
  3. 打印waiting: 2,进入2秒sleep阻塞
  4. 打印Task ret: Web is ok
  5. 程序总耗时约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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 14:48:03