aysncio cannot read stdin on Windows

前端 未结 1 647
渐次进展
渐次进展 2020-12-06 01:18

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          


        
相关标签:
1条回答
  • 2020-12-06 01:57

    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.

    0 讨论(0)
提交回复
热议问题