Python: How to read stdout of subprocess in a nonblocking way

前端 未结 2 720
予麋鹿
予麋鹿 2020-12-16 02:38

I am trying to make a simple python script that starts a subprocess and monitors its standard output. Here is a snippet from the code:

process = subprocess.P         


        
2条回答
  •  Happy的楠姐
    2020-12-16 02:59

    Check select module

    import subprocess
    import select
    import time
        
    x=subprocess.Popen(['/bin/bash','-c',"while true; do sleep 5; echo yes; done"],stdout=subprocess.PIPE)
        
    y=select.poll()
    y.register(x.stdout,select.POLLIN)
    
    while True:
      if y.poll(1):
         print x.stdout.readline()
      else:
         print "nothing here"
         time.sleep(1)
    

    EDIT:

    Threaded Solution for non posix systems:

    import subprocess
    from threading import Thread 
    import time
     
    linebuffer=[]
    x=subprocess.Popen(['/bin/bash','-c',"while true; do sleep 5; echo yes; done"],stdout=subprocess.PIPE)
    
    def reader(f,buffer):
       while True:
         line=f.readline()
         if line:
            buffer.append(line)
         else:
            break
    
    t=Thread(target=reader,args=(x.stdout,linebuffer))
    t.daemon=True
    t.start()
    
    while True:
      if linebuffer:
         print linebuffer.pop(0)
      else:
         print "nothing here"
         time.sleep(1)
    

提交回复
热议问题