Is there a better way to control the PYTHONPATH of a subprocess?
<p>I have a set of scripts that has to modify os.sys.path on the fly.  The scripts then kick off a subprocess.   Ideally, the subprocess would have the same os.sys.path as the caller.  I want to avoid passing it in as an argument, since that would require a modification to the subprocess script.</p>

<p>I have code that works and meets all of my needs.  I want to know if there is a better way to do this, and if there are any pitfalls to this approach.</p>

<p>The main process</p>

<pre><code>import os
import sys
import subprocess

#append a dir thats not on the sys path
sys.path.append('C:/pytest2/')

#convert the sys.path into env variable format
pypath = ''
for d in sys.path:
    pypath = pypath + d + ';'

#create a temp copy of the env variables
myenv = os.environ.copy()

#set PYTHONPATH to match this scripts sys.path
myenv['PYTHONPATH'] = pypath

#setup a python command to echo the sys.path
command = 'python C:/pytest/test_subprocess.py'

#launch the subprocess with the custom env
p = subprocess.Popen(command, env=myenv)
</code></pre>

<p>C:/pytest/test_subprocess.py</p>

<pre><code>import sys
print 'sys path'
print sys.path
</code></pre>

<p>Running the main process results in this console output</p>

<p><img src="http://i.stack.imgur.com/jgqRB.png" alt="enter image description here"></p>

<p>As you can see, C:/pytest2/ is on the os.sys.path for test_subprocess.py</p>

<p><strong>EDIT</strong>  Changed os.sys to sys</p>
