Search code examples
python-asyncio

Python async input


I'm trying to perform some actions during getting input from a user. I found this question but both answers not working for me.

My code:

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)

I'm expecting that input will be accessible during sleeping (or simple counting for example), but it's not happening. What I do wrong?


Solution

  • What I do wrong?

    You used await, which (as the name implies) means "wait". If you want things to happen at the same time, you need to tell them to run in the background, e.g. using asyncio.create_task() or concurrently, e.g. using asyncio.gather(). For example:

    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())