title: Run Python script within Python by using `subprocess.Popen` in real time
body: <p>I want to run a Python script (or any executable, for that manner) from a python script and get the output <em>in real time</em>. I have followed many tutorials, and my current code looks like this:</p>
  
  <pre class="lang-py prettyprint-override"><code>import subprocess
  with open("test2", "w") as f:
      f.write("""import time
  print('start')
  time.sleep(5)
  print('done')""")
  
  process = subprocess.Popen(['python3', "test2"], stdout=subprocess.PIPE)
  while True:
          output = process.stdout.readline()
          if output == '' and process.poll() is not None:
              break
          if output:
              print(output.strip())
          rc = process.poll()
  </code></pre>
  
  <p>The first bit just creates the file that will be run, for clarity's sake. </p>
  
  <p>I have two problems with this code:</p>
  
  <ul>
  <li><p>It does not give the output in real time. It waits untill the process has finished. </p></li>
  <li><p>It does not terminate the loop once the process has finished.</p></li>
  </ul>
  
  <p>Any help would be very welcome.</p>
  
  <p>EDIT: Thanks to @JohnAnderson for the fix to the first problem: replacing <code>if output == '' and process.poll() is not None:</code> with <code>if output == b'' and process.poll() is not None:</code></p>