title: How to get PID via subprocess.Popen with custom environment variable?
body: <p>Using Python, how can I run a subprocess with a modified environment variable and get its PID? I assume subprocess.Popen() is along the right track...</p>
  
  <p>In shell (bash), I would do this:</p>
  
  <pre><code>MY_ENV_VAR=value ./program_name arg1 arg2 etc &amp;
  </code></pre>
  
  <p>This runs <code>program_name</code> in the background, passing in "arg1" and "arg2" and "etc", with a modified environment variable, "MY_ENV_VAR" with a value of "value". The program <code>program_name</code> requires the environment variable <code>MY_ENV_VAR</code> to be set to the proper value.</p>
  
  <p>How can do the equivalent thing in Python? I absolutely need the PID of the process. (My intent is to keep the python script running and performing checks on some of the things <code>program_name</code> is doing in the meantime, and I need the process ID to make sure it's still running.)</p>
  
  <p>I've tried:</p>
  
  <pre><code>proc = subprocess.Popen(['MY_ENV_VAR=value', './program_name', 'arg1', 'arg2', 'etc'])
  </code></pre>
  
  <p>But of course, it expects the first item to be the program, not an environment variable.</p>
  
  <p>Also tried:</p>
  
  <pre><code>environ = dict(os.environ)
  environ['MY_ENV_VAR'] = 'value'
  proc = subprocess.Popen(['./program_name', 'arg1', 'arg2', 'etc', env=environ])
  </code></pre>
  
  <p>Close, I suppose, but no cigar. Similarly, this:</p>
  
  <pre><code>environ = dict(os.environ)
  environ['MY_ENV_VAR'] = 'value'
  proc = subprocess.Popen(['echo', '$MY_ENV_VAR'], env=environ)
  </code></pre>
  
  <p>This echoes "$MY_ENV_VAR" literally, I suppose because there's no shell to interpret it. Okay, so I try the above but with this line instead:</p>
  
  <pre><code>proc = subprocess.Popen(['echo', '$MY_ENV_VAR'], env=environ, shell=True)
  </code></pre>
  
  <p>And that's fine and dandy, except that the value that's echoed is blank (doesn't apparently exist). And even if it did work, I'd get the PID of the shell, not the actual process I'm trying to launch.</p>
  
  <p>I need to launch a process with a custom environment variable and get its PID (not the PID of the shell). Ideas?</p>