title: Controlling a python script from another script
body: <p>I am trying to learn how to write a script <code>control.py</code>, that runs another script <code>test.py</code> in a loop for a certain number of times, in each run, reads its output and halts it if some predefined output is printed (e.g. the text 'stop now'), and the loop continues its iteration (once <code>test.py</code> has finished, either on its own, or by force). So something along the lines:</p>
  
  <pre><code>for i in range(n):
      os.system('test.py someargument')
      if output == 'stop now': #stop the current test.py process and continue with next iteration
      #output here is supposed to contain what test.py prints
  </code></pre>
  
  <ul>
  <li>The problem with the above is that, it does not check the output of <code>test.py</code> as it is running, instead it waits until <code>test.py</code> process is finished on its own, right?</li>
  <li>Basically trying to learn how I can use a python script to control another one, as it is running. (e.g. having access to what it prints and so on).</li>
  <li>Finally, is it possible to run <code>test.py</code> in a new terminal (i.e. not in <code>control.py</code>'s terminal) and still achieve the above goals?</li>
  </ul>
  
  <hr>
  
  <p><strong>An attempt:</strong>
  <code>test.py</code> is this:</p>
  
  <pre><code>from itertools import permutations
  import random as random
  
  
  perms = [''.join(p) for p in permutations('stop')]
  
  for i in range(1000000):
      rand_ind = random.randrange(0,len(perms))
      print perms[rand_ind]
  </code></pre>
  
  <p>And <code>control.py</code> is this: (following Marc's suggestion)</p>
  
  <pre><code>import subprocess
  
  command = ["python", "test.py"]
  n = 10
  for i in range(n):
      p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
      while True:
          output = p.stdout.readline().strip()
          print output
          #if output == '' and p.poll() is not None:
          #    break
          if output == 'stop':
              print 'sucess'
              p.kill()
              break
              #Do whatever you want
      #rc = p.poll() #Exit Code
  </code></pre>