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

后端 未结 29 2730
醉酒成梦
醉酒成梦 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条回答
  •  Happy的楠姐
    2020-11-21 05:04

    EDIT: This implementation still blocks. Use J.F.Sebastian's answer instead.

    I tried the top answer, but the additional risk and maintenance of thread code was worrisome.

    Looking through the io module (and being limited to 2.6), I found BufferedReader. This is my threadless, non-blocking solution.

    import io
    from subprocess import PIPE, Popen
    
    p = Popen(['myprogram.exe'], stdout=PIPE)
    
    SLEEP_DELAY = 0.001
    
    # Create an io.BufferedReader on the file descriptor for stdout
    with io.open(p.stdout.fileno(), 'rb', closefd=False) as buffer:
      while p.poll() == None:
          time.sleep(SLEEP_DELAY)
          while '\n' in bufferedStdout.peek(bufferedStdout.buffer_size):
              line = buffer.readline()
              # do stuff with the line
    
      # Handle any remaining output after the process has ended
      while buffer.peek():
        line = buffer.readline()
        # do stuff with the line
    

提交回复
热议问题