A non-blocking read on a subprocess.PIPE in Python

后端 未结 29 2564
醉酒成梦
醉酒成梦 2020-11-21 04:49

I\'m using the subprocess module to start a subprocess and connect to its output stream (standard output). I want to be able to execute non-blocking reads on its standard ou

29条回答
  •  执笔经年
    2020-11-21 04:54

    Things are a lot better in modern Python.

    Here's a simple child program, "hello.py":

    #!/usr/bin/env python3
    
    while True:
        i = input()
        if i == "quit":
            break
        print(f"hello {i}")
    

    And a program to interact with it:

    import asyncio
    
    
    async def main():
        proc = await asyncio.subprocess.create_subprocess_exec(
            "./hello.py", stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE
        )
        proc.stdin.write(b"bob\n")
        print(await proc.stdout.read(1024))
        proc.stdin.write(b"alice\n")
        print(await proc.stdout.read(1024))
        proc.stdin.write(b"quit\n")
        await proc.wait()
    
    
    asyncio.run(main())
    

    That prints out:

    b'hello bob\n'
    b'hello alice\n'
    

    Note that the actual pattern, which is also by almost all of the previous answers, both here and in related questions, is to set the child's stdout file descriptor to non-blocking and then poll it in some sort of select loop. These days, of course, that loop is provided by asyncio.

提交回复
热议问题