Last active
September 6, 2017 02:02
-
-
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
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
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