I'm trying to read stdin asynchronously on Windows 7 64-bit and Python 3.4.3
I tried this inspired by an SO answer:
import asyncio
import sys
def reader():
print('Received:', sys.stdin.readline())
loop = asyncio.get_event_loop()
task = loop.add_reader(sys.stdin.fileno(), reader)
loop.run_forever()
loop.close()
However, it raises an OSError: [WInError 100381] An operation was attempted on something that is not a socket
.
Could a file-like object like stdin
be wrapped in a class to give it the API of a socket? I have asked this question separately, but if the solution is simple please answer here.
Assuming that I cannot wrap a file-like object to make it a socket, I tried using streams as inspired by this gist:
import asyncio
import sys
@asyncio.coroutine
def stdio(loop):
reader = asyncio.StreamReader(loop=loop)
reader_protocol = asyncio.StreamReaderProtocol(reader)
yield from loop.connect_read_pipe(lambda: reader_protocol, sys.stdin)
@asyncio.coroutine
def async_input(loop):
reader = yield from stdio(loop)
line = yield from reader.readline()
return line.decode().replace('
', '').replace('
', '')
@asyncio.coroutine
def main(loop):
name = yield from async_input(loop)
print('Hello ', name)
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
loop.close()
And that raises a NotImplementedError
in asyncio.base_events._make_read_pipe_transport
Please advise how to read stdin
using asyncio
on Windows...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…