title: Python subprocess module, how do I give input to the first of series of piped commands?
body: <p>I am trying to use Python's subprocess module. What I require is to send input to the first process whose output becomes the input of the second process.
  The situation is basically almost the same as the example given in the documentation here:
  <a href="http://docs.python.org/library/subprocess.html#replacing-shell-pipeline" rel="noreferrer">http://docs.python.org/library/subprocess.html#replacing-shell-pipeline</a>
  except that I need to provide input the first command.
  Here is that example copied:</p>
  
  <pre><code>p1 = Popen(["dmesg"], stdout=PIPE)
  p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
  p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
  output = p2.communicate()[0]
  </code></pre>
  
  <p>If we change the first line to:</p>
  
  <pre><code>p1 = Popen(["cat"], stdout=PIPE, stdin=PIPE)
  </code></pre>
  
  <p>How do I provide the input string to the process?
  If I attempt it by changing the final line to:</p>
  
  <pre><code>output = p2.communicate(input=inputstring)[0]
  </code></pre>
  
  <p>This doesn't work.</p>
  
  <p>I do have a working version, which just stores the output of the first command in a string and then passes that to the second command. This isn't terrible as there is essentially no concurrency that can be exploited (in my actual use case the first command will exit rather quickly and produce all of its output at the end).
  Here is the working version in full:</p>
  
  <pre><code>import subprocess
  
  simple = """Writing some text
  with some lines in which the
  word line occurs but others
  where it does
  not
  """
  
  def run ():
    catcommand = [ "cat" ]
    catprocess = subprocess.Popen(catcommand,
                                  stdin=subprocess.PIPE,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE)
    (catout, caterr) = catprocess.communicate(input=simple)
    grepcommand = [ "grep", "line" ]
    grepprocess = subprocess.Popen(grepcommand,
                                  stdin=subprocess.PIPE,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE)
    (grepout, greperr) = grepprocess.communicate(input=catout)
    print "--- output ----"
    print grepout 
    print "--- error ----"
    print greperr 
  
  if __name__ == "__main__":
    run()
  </code></pre>
  
  <p>I hope I've been clear enough, thanks for any help.</p>