I'm trying to write a concurrent Python program using asyncio
that also accepts keyboard input. The problem appears when I try to shut down my program. Since keyboard input is in the end done with sys.stdin.readline
, that function only returns after I press ENTER
, regardless if I stop()
the event loop or cancel()
the function's Future
.
Is there any way to provide keyboard input with asyncio
that can be canceled?
Here is my MWE. It will accept keyboard inputs for 1 second, then stop()
:
import asyncio
import sys
async def console_input_loop():
while True:
inp = await loop.run_in_executor(None, sys.stdin.readline)
print(f"[{inp.strip()}]")
async def sleeper():
await asyncio.sleep(1)
print("stop")
loop.stop()
loop = asyncio.get_event_loop()
loop.create_task(console_input_loop())
loop.create_task(sleeper())
loop.run_forever()