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

后端 未结 29 2572
醉酒成梦
醉酒成梦 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 05:14

    why bothering thread&queue? unlike readline(), BufferedReader.read1() wont block waiting for \r\n, it returns ASAP if there is any output coming in.

    #!/usr/bin/python
    from subprocess import Popen, PIPE, STDOUT
    import io
    
    def __main__():
        try:
            p = Popen( ["ping", "-n", "3", "127.0.0.1"], stdin=PIPE, stdout=PIPE, stderr=STDOUT )
        except: print("Popen failed"); quit()
        sout = io.open(p.stdout.fileno(), 'rb', closefd=False)
        while True:
            buf = sout.read1(1024)
            if len(buf) == 0: break
            print buf,
    
    if __name__ == '__main__':
        __main__()
    

提交回复
热议问题