如何在主线程非阻塞调用含aioconsole的异步函数?
在主线程调用含await的异步函数时避免阻塞计算逻辑的问题
需要在主线程中调用包含await的异步函数,同时不阻塞主线程的计算逻辑。尝试了多种解决方案,以下两种在aioconsole和asyncio环境下均无法正常工作。
当前简化实现
import aioconsole import asyncio async def async_input(): line = await aioconsole.ainput(">>> ") print("You typed: " + line) if __name__ == "__main__": asyncio.run(async_input()) print("This text should print instantly. It should not wait for you to type something in the console.") while True: # Do stuff here pass
尝试过的替代方案
曾将asyncio.run(async_input())替换为以下代码,但程序在输入控制台内容后仍会挂起:
loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.create_task(async_input()) loop.run_forever()
当前现象
- 函数已创建 ✓
- 已从主线程调用函数 ✓
- 程序暂停并等待异步函数完成 ✗
- 本应与异步函数并行的处理逻辑变为串行执行 ✗
当前输出:
>>>
预期效果
- 函数已创建 ✓
- 已从主线程调用函数 ✓
- 程序继续执行,异步函数在后台运行 ✓
- 后续处理逻辑与异步函数并行执行 ✓
预期输出:
>>> This text should print instantly. It should not wait for you to type something in the console.
环境信息
- Python版本:3.10.8
- 操作系统:MacOS Ventura
内容的提问来源于stack exchange,提问作者Leon
相关产品推荐
相关产品推荐

