Skip to content

Instantly share code, notes, and snippets.

@delivrance
Last active December 9, 2022 23:47
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Python async input
import asyncio
from concurrent.futures import ThreadPoolExecutor
async def ainput(prompt: str = "") -> str:
with ThreadPoolExecutor(1, "AsyncInput") as executor:
return await asyncio.get_event_loop().run_in_executor(executor, input, prompt)
async def main():
name = await ainput("What's your name? ")
print(f"Hello, {name}!")
asyncio.run(main())
@Trogious
Copy link

Trogious commented Jan 11, 2021

Why readline() and not: input()on line 9?

@Trogious
Copy link

My version:

async def ainput(prompt: str = ''):
    with ThreadPoolExecutor(1, 'ainput') as executor:
        return (await asyncio.get_event_loop().run_in_executor(executor, input, prompt)).rstrip()

@delivrance
Copy link
Author

Cannot remember why, as years have passed since.

This snippet is being useful in Pyrogram, in which I indeed eventually switched to using input and getpass as functions to be run in the executor. The use of sys.stdin.readline and the thread initializer definitely looks unnecessary.

Gist updated with a simplified version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment