title: Keeping a pipe to a process open
body: <p>I have an <code>app</code> that reads in stuff from <code>stdin</code> and returns, after a newline, results to <code>stdout</code></p>
  
  <p>A simple (stupid) example:</p>
  
  <pre><code>$ app
  Expand[(x+1)^2]&lt;CR&gt;
  x^2 + 2*x + 1
  100 - 4&lt;CR&gt;
  96
  </code></pre>
  
  <p>Opening and closing the <code>app</code> requires a lot of initialization and clean-up (its an interface to a Computer Algebra System), so I want to keep this to a minimum.</p>
  
  <p>I want to open a pipe in Python to this process, write strings to its <code>stdin</code> and read out the results from <code>stdout</code>. <code>Popen.communicate()</code> doesn't work for this, as it closes the file handle, requiring to reopen the pipe. </p>
  
  <p>I've tried something along the lines of this related question: 
  <a href="https://stackoverflow.com/questions/3065060/communicate-multiple-times-with-a-process-without-breaking-the-pipe">Communicate multiple times with a process without breaking the pipe?</a> but I'm not sure how to wait for the output. It is also difficult to know a priori how long it will take the <code>app</code> to finish to process for the input at hand, so I don't want to make any assumptions. I guess most of my confusion comes from this question: <a href="https://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python">Non-blocking read on a subprocess.PIPE in python</a> where it is stated that mixing high and low level functions is not a good idea.</p>
  
  <p><strong>EDIT</strong>:
  Sorry that I didn't give any code before, got interrupted. This is what I've tried so far and it seems to work, I'm just worried that something goes wrong unnoticed:</p>
  
  <pre><code>from subprocess import Popen, PIPE
  pipe = Popen(["MathPipe"], stdin=PIPE, stdout=PIPE)         
  expressions = ["Expand[(x+1)^2]", "Integrate[Sin[x], {x,0,2*Pi}]"] # ...                                                                                        
  for expr in expressions:
      pipe.stdin.write(expr)                                                        
      while True:                                                                         
          line = pipe.stdout.readline()                                                    
          if line != '':     
              print line  
          # output of MathPipe is always terminated by ';'                                                                                                                         
          if ";" in line:                                                                  
              break                                                                       
  </code></pre>
  
  <p>Potential problems with this?</p>