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

后端 未结 29 2661
醉酒成梦
醉酒成梦 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:50

    Use select & read(1).

    import subprocess     #no new requirements
    def readAllSoFar(proc, retVal=''): 
      while (select.select([proc.stdout],[],[],0)[0]!=[]):   
        retVal+=proc.stdout.read(1)
      return retVal
    p = subprocess.Popen(['/bin/ls'], stdout=subprocess.PIPE)
    while not p.poll():
      print (readAllSoFar(p))
    

    For readline()-like:

    lines = ['']
    while not p.poll():
      lines = readAllSoFar(p, lines[-1]).split('\n')
      for a in range(len(lines)-1):
        print a
    lines = readAllSoFar(p, lines[-1]).split('\n')
    for a in range(len(lines)-1):
      print a
    

提交回复
热议问题