title: python, iterate on subprocess.Popen() stdout/stderr
body: <p>There are a lot of similar posts, but I didn't find answer.</p>
  
  <p>On Gnu/Linux, with <code>Python</code> and <code>subprocess</code> module, I use the following code to iterate over the
  stdout/sdterr of a command launched with subprocess:</p>
  
  <pre><code>class Shell:
      """ 
      run a command and iterate over the stdout/stderr lines
      """
  
      def __init__(self):
  
          pass
  
      def __call__(self,args,cwd='./'):
  
          p = subprocess.Popen(args,
                  cwd=cwd, 
                  stdout = subprocess.PIPE,
                  stderr = subprocess.STDOUT,
                  )
  
          while True:
  
              line = p.stdout.readline()
              self.code = p.poll()
  
              if line == '':
                  if self.code != None:
                      break
                  else:
                      continue
  
              yield line
  
  #example of use
  args = ["./foo"]
  shell = Shell()
  for line in shell(args):
       #do something with line
       print line,
  </code></pre>
  
  <p>This works fine... except if the command executed is <code>python</code>, for example `args = ['python','foo.py'], in which case the output is not flushed but printed only when the command is finished.</p>
  
  <p>Is there a solution?</p>