Skip to content

Instantly share code, notes, and snippets.

@datavudeja
Forked from sheilatron/python_popen_python.py
Created February 9, 2025 22:11
Show Gist options
  • Save datavudeja/0e302f18a46d3f6486ca4d772a05c75f to your computer and use it in GitHub Desktop.
Save datavudeja/0e302f18a46d3f6486ca4d772a05c75f 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