title: Python - Run process and wait for output
body: <p>I want to run a program, wait for it's output, send inputs to it and repeat until a condition.  </p>
  
  <p>All I could find was questions about waiting for a program to finish, which is NOT the case. The process will still be running, it just won't be giving any (new) outputs.  </p>
  
  <p>Program output is in stdout and in a log file, either can be used.<br>
  Using linux.</p>
  
  <p>Code so far:  </p>
  
  <pre><code>import subprocess
  
  flag = True
  vsim = subprocess.popen(['./run_vsim'], 
                          stdin=subprocess.pipe,
                          shell=true, 
                          cwd='path/to/program')
  while flag:
      with open(log_file), 'r') as f:
          for l in f:
              if condition:
                  break
      vsim.stdin.write(b'do something\n')
      vsim.stdin.flush()
  vsim.stdin.write(b'do something else\n')
  vsim.stdin.flush()
  </code></pre>
  
  <p>As is, the "do something" input is being sent multiple times even before the program finished starting up. Also, the log file is read before the program finishes running the command from the last while iteraction. That causes it to buffer the inputs, so I keeps executing the commands even after the condition as been met.  </p>
  
  <p>I could use <code>time.sleep</code> after each <code>stdin.write</code> but since the time needed to execute each command is variable, I would need to use times longer than necessary making the python script slower. Also, that's a dumb solution to this.</p>
  
  <p>Thanks!</p>