Skip to content

Instantly share code, notes, and snippets.

@sheilatron
Created March 21, 2012 14:13
Show Gist options
  • Save sheilatron/2147199 to your computer and use it in GitHub Desktop.
Save sheilatron/2147199 to your computer and use it in GitHub Desktop.
Python function to create child Python processes inheriting sys.paths
def spawn_python_script(package_name, script_name, *args):
"""
Run the module ``script_name`` as an external Python script,
using the same Python executable as the current process,
with the same Python paths. This needs to support both
virtualenv and buildout Python executables.
Example:
popen = run_as_script('zetl.scripts','start_conductor.py')
Returns a :class:`subprocess.Popen` instance.
The `args` will be added as command line arguments.
"""
script_path = resource_filename(package_name, script_name)
if args:
params = [sys.executable, script_path] + list(args)
else:
params = [sys.executable, script_path]
# Build the PYTHONPATH environment variable needed by the child process
# in order to acquire the same sys.path values of the parent process.
python_path = ":".join(sys.path)[1:] # strip leading colon
logger.info( "Running %s", params)
return subprocess.Popen(params, env={'PYTHONPATH':python_path})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment