Python async: Waiting for stdin input while doing other stuff

Borrowing heavily from aioconsole, if you would rather avoid using an external library you could define your own async input function:

async def ainput(string: str) -> str:
    await asyncio.get_event_loop().run_in_executor(
            None, lambda s=string: sys.stdout.write(s+' '))
    return await asyncio.get_event_loop().run_in_executor(
            None, sys.stdin.readline)

Leave a Comment