title: Multiple inputs and outputs in python subprocess communicate
body: <p>I need to do something like <a href="https://stackoverflow.com/questions/163542/python-how-do-i-pass-a-string-into-subprocess-popen-using-the-stdin-argument">this post</a>, but I need to create a subprocess that can be given input and give output many times. The accepted answer of that post has good code...</p>
  
  <pre><code>from subprocess import Popen, PIPE, STDOUT
  
  p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)    
  grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0]
  print(grep_stdout.decode())
  
  # four
  # five
  </code></pre>
  
  <p>...that I would like to continue like this:</p>
  
  <pre><code>grep_stdout2 = p.communicate(input=b'spam\neggs\nfrench fries\nbacon\nspam\nspam\n')[0]
  print(grep_stdout2.decode())
  
  # french fries
  </code></pre>
  
  <p>But alas, I get the following error:</p>
  
  <pre><code>Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 928, in communicate
      raise ValueError("Cannot send input after starting communication")
  ValueError: Cannot send input after starting communication
  </code></pre>
  
  <p>The proc.stdin.write() method not enable you to collect output, if I understand correctly. What is the simplest way to keep the lines open for ongoing input/output?</p>
  
  <p><strong>Edit: ====================</strong></p>
  
  <p>It looks like <code>pexpect</code> is a useful library for what I am trying to do, but I am having trouble getting it to work. Here is a more complete explanation of my actual task. I am using <code>hfst</code> to get grammar analyses of individual (Russian) words. The following demonstrates its behavior in a bash shell:</p>
  
  <pre><code>$ hfst-lookup analyser-gt-desc.hfstol
  &gt; слово
  слово   слово+N+Neu+Inan+Sg+Acc 0.000000
  слово   слово+N+Neu+Inan+Sg+Nom 0.000000
  
  &gt; сработай
  сработай    сработать+V+Perf+IV+Imp+Sg2 0.000000
  сработай    сработать+V+Perf+TV+Imp+Sg2 0.000000
  
  &gt; 
  </code></pre>
  
  <p>I want my script to be able to get the analyses of one form at a time. I tried code like this, but it is not working.</p>
  
  <pre><code>import pexpect
  
  analyzer = pexpect.spawnu('hfst-lookup analyser-gt-desc.hfstol')
  for newWord in ['слово','сработай'] :
      print('Trying', newWord, '...')
      analyzer.expect('&gt; ')
      analyzer.sendline( newWord )
      print(analyzer.before)
  
  # trying слово ...
  # 
  # trying сработай ...
  # слово
  # слово слово+N+Neu+Inan+Sg+Acc 0.000000
  # слово слово+N+Neu+Inan+Sg+Nom 0.000000
  # 
  # 
  </code></pre>
  
  <p>I obviously have misunderstood what <code>pexpect.before</code> does. How can I get the output for each word, one at a time?</p>