title: Get the output of multiple commands from subprocess.Popen
body: <p>I am trying to run a command, get it's output, then later run another command in the same environment (say if I set an environment variable in the first command, I want it to be available to the second command). I tried this:</p>
  
  <pre><code>import subprocess
  
  process = subprocess.Popen("/bin/bash", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
  
  process.stdin.write("export MyVar=\"Test\"\n")
  process.stdin.write("echo $MyVar\n")
  process.stdin.flush()
  
  stdout, stderr  = process.communicate()
  print "stdout: " + str(stdout)
  
  # Do it again
  process.stdin.write("echo $MyVar\n")
  process.stdin.flush()
  
  stdout, stderr = process.communicate()
  print "stdout: " + str(stdout)
  </code></pre>
  
  <p>but communicate() reads until the end, so this is not a valid technique. (I get this:)</p>
  
  <pre><code>stdout: Test
  
  Traceback (most recent call last):
    File "./MultipleCommands.py", line 15, in &lt;module&gt;
      process.stdin.write("echo $MyVar\n")
  ValueError: I/O operation on closed file
  </code></pre>
  
  <p>I have seen this: <a href="https://stackoverflow.com/a/15654218/284529">https://stackoverflow.com/a/15654218/284529</a> , but it doesn't give a working example of how to do what it proposes. Can anyone demonstrate how to do this?
  I have also seen other techniques that involve constantly checking for output in a loop, but this doesn't fit the "get the output of a command" mentality - it is just treating it like a stream.</p>