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

异步函数中Python print无输出问题求助

问题分析与解决方案

核心问题

你的异步代码没有实际启动asyncio事件循环,同时在协程内使用了同步阻塞的time.sleep(),导致协程从未被调度执行,因此没有任何输出。

具体问题点

  • 事件循环未启动:你仅用loop.create_task(main())创建了任务,但未调用事件循环的运行方法(如loop.run_forever()),而time.sleep(5)是同步阻塞操作,这段时间里事件循环完全没有机会处理任务。
  • 协程内误用同步sleep:在异步协程main()中使用time.sleep(0.05)会阻塞整个事件循环,即使事件循环启动,也无法实现异步调度的效果。

修复后的代码

import asyncio, os, sys, time

def update(text):
    global print
    print("", flush=True)
    os.system("clear")
    print(text, flush=True)
    print("What is your selection? ", flush=True)

async def main():
    a = "a"
    while True:
        update(a)
        a += "c"
        await asyncio.sleep(0.05)  # 替换为异步sleep,让出控制权

loop = asyncio.get_event_loop()
main_task = loop.create_task(main())

# 创建5秒后自动终止任务的协程
async def stop_after_timeout():
    await asyncio.sleep(5)
    main_task.cancel()

loop.create_task(stop_after_timeout())

try:
    loop.run_forever()
except asyncio.CancelledError:
    pass
finally:
    loop.close()

关键修改说明

  • 用await asyncio.sleep(0.05)替代time.sleep(0.05):让协程主动让出事件循环控制权,保证异步调度正常进行。
  • 启动事件循环并添加超时终止逻辑:通过额外的协程实现5秒后取消主任务,再调用loop.run_forever()让事件循环持续运行直到任务被取消。
  • 移除同步time.sleep(5):避免阻塞事件循环的启动和任务调度。

Python 3.7+ 简化写法

如果使用Python 3.7及以上版本,可借助asyncio.run()简化代码:

import asyncio, os

def update(text):
    print("", flush=True)
    os.system("clear")
    print(text, flush=True)
    print("What is your selection? ", flush=True)

async def main():
    a = "a"
    try:
        while True:
            update(a)
            a += "c"
            await asyncio.sleep(0.05)
    except asyncio.CancelledError:
        pass

async def run_with_timeout():
    main_task = asyncio.create_task(main())
    await asyncio.sleep(5)
    main_task.cancel()
    await main_task

asyncio.run(run_with_timeout())

内容的提问来源于stack exchange,提问作者py660

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 06:43:25