Skip to content

Instantly share code, notes, and snippets.

@henry232323
Last active September 6, 2017 02:02
Show Gist options
  • Save henry232323/cf15f04fd5d3d4fe20d6a69bcad52b16 to your computer and use it in GitHub Desktop.
Save henry232323/cf15f04fd5d3d4fe20d6a69bcad52b16 to your computer and use it in GitHub Desktop.
Using sys.stdin with asyncio readers. Doesn't work on Windows because sys.stdin isn't a socket
import sys
import asyncio
from collections import deque
_loop = asyncio.get_event_loop()
_queue = deque()
def __reader(self):
data = sys.stdin.readline()
self._queue.popleft().set_result(data)
async def get_input(loop=None):
loop = loop or _loop
try:
future = loop.create_future()
_queue.append(future)
if not (len(_queue) - 1):
loop.call_soon(loop.add_reader, sys.stdin, __reader)
return await future
finally:
if not _queue:
loop.call_soon(loop.remove_reader, sys.stdin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment