If you are using subprocess.Popen to run an external process while running Python/Django with a virtual environment in Apache via mod_wsgi you’ll discover the new processes run outside of your virtual environment. In my case, I need to set the PYTHONPATH environment variable to get everything straight. Rather than hardcode it or the sys.path in the external script, I’d like to set it to the same value as the existing environment.

Here is a simple example of how an external process can be started while setting the an environment variable. A few print() statements have been added in there to give thorough details.

import os, sys
import subprocess

def start_process(command):
    # Get a copy of the existing environment.
    env = os.environ.copy()
    # Add the PYTHONPATH using the existing python system path.
    env['PYTHONPATH'] = ":".join(sys.path)

    proc = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        env=env,
    )
    # Get stdout and stderr from the process.
    (stdout, stderr) = proc.communicate()
    # Print the original environment.
    print("ENV:"+str(os.environ))
    # Print the system path.
    print("PATH:"+str(sys.path))
    print("STDOUT: " + stdout)
    print("STDERR: " + stderr)

start_process("uptime")

Am I doing this completely wrong? Maybe! Let me know in the comments. Thanks!

Related: A method to pass Apache Environment Variables to Django via mod_wsgi.