Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asyncio print something while waiting for user input

I have a simple script, I want the user to be able to input something whenever he wants, but I want to also print something out in the meantine, this is my code:

import asyncio

async def user_input():
   while True:
        content = input('> ')


async def print_something():
    await asyncio.sleep(10)
    print('something')


async def main():
    tasks = [user_input(), print_something()]
    await asyncio.gather(*tasks)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

It lets me input, but it doesn't print something, how can I achieve that?


1 Answers

input is a blocking function and cannot be used with inside coroutines straightforwardly. But you could start it in a separate thread by means of run_in_executor:

import asyncio


async def user_input():
    while True:
        loop = asyncio.get_event_loop()
        content = await loop.run_in_executor(None, input, "> ")
        print(content)


async def print_something():
    await asyncio.sleep(5)
    print('something')


async def main():
    tasks = [user_input(), print_something()]
    await asyncio.gather(*tasks)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

Update: Also you can use aioconsole lib, which provides asyncio-based console functions:

from aioconsole import ainput

async def user_input():
    while True:
        content = await ainput(">")
        print(content)
like image 160
alex_noname Avatar answered Mar 23 '26 03:03

alex_noname



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!