0

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?

salius
  • 918
  • 1
  • 14
  • 30

2 Answers2

2

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())
user4815162342
  • 141,790
  • 18
  • 296
  • 355
0

If you want to use the asyncio library, user4815162342 provided a great solution. But if you want to use threading, you could create a separate thread for handling input like this:

import threading


def write():
    while True:
        input()


def handle():
    #logic or whatever


write_thread = threading.Thread(target=write)
handle_thread = threading.Thread(target=handle)
write_thread.start()
handle_thread.start()