Python 异步输入

Python async input

我正在尝试在获取用户输入的过程中执行一些操作。我找到了 个问题,但两个答案都不适合我。

我的代码:

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)

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

What I do wrong?

您使用了await,它(顾名思义)的意思是“等待”。如果你想让事情同时发生,你需要在后台告诉他们 运行,例如使用 asyncio.create_task() 或同时使用,例如使用 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())