首页 > 解决方案 > Python 异步输入

问题描述

我正在尝试在获取用户输入期间执行一些操作。我发现了这个问题,但两个答案都不适合我。

我的代码:

In [1]: import asyncio 
In [2]: import aioconsole
In [3]:
In [3]:
In [3]: async def test(): 
    ...:     await asyncio.sleep(5) 
    ...:     await aioconsole.ainput('Is this your line? ') 
    ...:     await asyncio.sleep(5) 
In [4]: asyncio.run(test())  # sleeping, input, sleeping (synchronously)

我期望在睡眠期间可以访问输入(或例如简单的计数),但它没有发生。我做错了什么?

标签: python-asyncio

解决方案


我做错了什么?

您使用await了 ,(顾名思义)表示“等待”。如果您希望事情同时发生,您需要告诉它们在后台运行,例如 usingasyncio.create_task()或并发,例如 using asyncio.gather()。例如:

async def say_hi(message):
    await asyncio.sleep(1)
    print(message)

async def test():
    _, response, _ = await asyncio.gather(
        say_hi("hello"),
        aioconsole.ainput('Is this your line? '),
        say_hi("world"),
    )
    print("response was", response)

asyncio.run(test())

推荐阅读