title: Interactive input/output using Python
body: <p>I have a program that interacts with the user (acts like a shell), and I want to run it using the Python subprocess module interactively.
  That means, I want the possibility to write to standard input and immediately get the output from standard output. I tried many solutions offered here, but none of them seems to work for my needs.</p>
  <p>The code I've written is based on <em><a href="https://stackoverflow.com/questions/11457931/running-an-interactive-command-from-within-python">Running an interactive command from within Python</a></em>.</p>
  <pre><code>import Queue
  import threading
  import subprocess
  def enqueue_output(out, queue):
      for line in iter(out.readline, b''):
          queue.put(line)
      out.close()
  
  def getOutput(outQueue):
      outStr = ''
      try:
          while True: # Adds output from the queue until it is empty
              outStr += outQueue.get_nowait()
  
      except Queue.Empty:
          return outStr
  
  p = subprocess.Popen(&quot;./a.out&quot;, stdin=subprocess.PIPE, stout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize = 1)
  #p = subprocess.Popen(&quot;./a.out&quot;, stdin=subprocess.PIPE, stout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, universal_newlines=True)
  
  outQueue = Queue()
  errQueue = Queue()
  
  outThread = Thread(target=enqueue_output, args=(p.stdout, outQueue))
  errThread = Thread(target=enqueue_output, args=(p.stderr, errQueue))
  
  outThread.daemon = True
  errThread.daemon = True
  
  outThread.start()
  errThread.start()
  
  p.stdin.write(&quot;1\n&quot;)
  p.stdin.flush()
  errors = getOutput(errQueue)
  output = getOutput(outQueue)
  
  p.stdin.write(&quot;5\n&quot;)
  p.stdin.flush()
  erros = getOutput(errQueue)
  output = getOutput(outQueue)
  </code></pre>
  <p>The problem is that the queue remains empty, as if there is no output.
  Only if I write to standard input all the input that the program needs to execute and terminate, then I get the output (which is not what I want). For example, if I do something like:</p>
  <pre><code>p.stdin.write(&quot;1\n5\n&quot;)
  errors = getOutput(errQueue)
  output = getOutput(outQueue)
  </code></pre>
  <p>Is there a way to do what I want to do?</p>
  <hr/>
  <p>The script will run on a Linux machine. I changed my script and deleted the universal_newlines=True + set the bufsize to 1 and flushed standard input immediately after write. Still I don't get any output.</p>
  <p><strong>Second try:</strong></p>
  <p>I tried this solution and it works for me:</p>
  <pre><code>from subprocess import Popen, PIPE
  
  fw = open(&quot;tmpout&quot;, &quot;wb&quot;)
  fr = open(&quot;tmpout&quot;, &quot;r&quot;)
  p = Popen(&quot;./a.out&quot;, stdin = PIPE, stdout = fw, stderr = fw, bufsize = 1)
  p.stdin.write(&quot;1\n&quot;)
  out = fr.read()
  p.stdin.write(&quot;5\n&quot;)
  out = fr.read()
  fw.close()
  fr.close()
  </code></pre>