Python async input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
|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? ")|
Jan 11, 2021
async def ainput(prompt: str = ''): with ThreadPoolExecutor(1, 'ainput') as executor: return (await asyncio.get_event_loop().run_in_executor(executor, input, prompt)).rstrip()
Jan 12, 2021
Cannot remember why, as years have passed since.
This snippet is being useful in Pyrogram, in which I indeed eventually switched to using
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
Why readline() and not: input()on line 9?