title: Python subprocess - write multiple stdin
body: <p>I need to open an R script and supply it with input formulated by a separate python script. The <code>subprocess</code> module seems to be a good way to do this. </p>
  
  <p>I have encountered some puzzling results though, namely that I can apparently write once and only once via <code>p.stdin</code>.  Here is what I have so far: </p>
  
  <pre><code>from subprocess import Popen, PIPE, STDOUT
  
  p = Popen(['r --no-save'],stdin=PIPE,stdout=PIPE,stderr=PIPE,shell=True)
  p.stdin.write("source('myrscript.R')\n")
  p.stdin.write('myfirstinput')
  </code></pre>
  
  <p>What happens when I run this code is that the first instance of <code>stdin.write()</code> performs as expected (and opens my R script), but the second line does nothing, and the subprocess (really, the R script) exits with an error, indicating that the subprocessed received no input where input was expected and therefore terminated. </p>
  
  <p>N.B. -  In a perfect world, I would just interact directly through R, but this particular script requires complex inputs that cannot be entered directly for practical purposes. Also, rpy / rpy2 is not an option, because end-users of this script will not necessarily have access to that module or its dependencies. <code>rscript</code> is also not an option (for many reasons, but mainly because of variability in the end-users R configurations). </p>
  
  <p>Finally, <code>p.communicate</code> is not an option, because apparently that will close the process after writing and I need to keep it open. </p>
  
  <p>Thanks in advance</p>