aysncio cannot read stdin on Windows

£可爱£侵袭症+ 提交于 2019-11-28 09:12:09

The NotImplementedError exception is raised because the connect pipes coroutines are not supported by the SelectorEventLoop, which is the default event loop set on asyncio. You need to use a ProactorEventLoop to support pipes on Windows. However, it would still not work because apparently the connect_read_pipe and connect_write_pipe functions doesn't support stdin/stdout/stderr or files in Windows as Python 3.5.1.

One way to read from stdin with an asynchronous behavior is using a thread with the loop's run_in_executor method. Here is a simple example for reference:

import asyncio
import sys

async def aio_readline(loop):
    while True:
        line = await loop.run_in_executor(None, sys.stdin.readline)
        print('Got line:', line, end='')

loop = asyncio.get_event_loop()
loop.run_until_complete(aio_readline(loop))
loop.close()

In the example the function sys.stdin.readline() is called within another thread by the loop.run_in_executor method. The thread remains blocked until stdin receives a linefeed, in the mean time the loop is free to execute others coroutines if they existed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!