title: how to pass a pipe() descriptor to Python subprocess.Popen(), in any version of Python
body: <p>I want to spawn a child process in Python, whose standard streams are used for other purposes and I can't touch them, and I want to have a dedicated pipe for my own purposes, independent of standard streams.  </p>
  
  <p>In Python version 2, the following works:</p>
  
  <p><code>foobar.py</code>:</p>
  
  <pre><code>#!/usr/bin/python
  
  from os import pipe, environ, read
  import subprocess
  
  output, input = pipe()
  new_environ = environ.copy()
  new_environ["PIPE_INPUT"] = str(input)
  subprocess.Popen(['./a.out'], env=new_environ)
  print(read(output, 6))
  </code></pre>
  
  <p>and <code>a.out</code> is compiled from <code>foobar.c</code>:</p>
  
  <pre><code>#include &lt;unistd.h&gt;
  #include &lt;stdlib.h&gt;
  
  void main() {
      write(atoi(getenv("PIPE_INPUT")), "foobar", 6);
  }
  </code></pre>
  
  <p>This works, <code>./foobar.py</code> prints <code>foobar</code>. </p>
  
  <p>But, with the shebang line</p>
  
  <pre><code>#!/usr/bin/python3
  </code></pre>
  
  <p>it does not work.  Of course, this is because, according to the docs, in Python 3 the descriptors are not inheritable.  </p>
  
  <p>Well, then how do I do this in Python 3, and also so that the same code works for Python 2.  I cannot have different code for different Pythons, has to be portable code for Python 2 and 3.  </p>