I am creating a new child terminal and passing it the calling shell's environment variables using:
currentEnv =os.environ.copy()
print("PARENT: " + currentEnv["PATH"])
subprocess.Popen(shlex.split("sudo gnome-terminal -x bash -c 'python3 somescript.py'"), env=currentEnv)
inside somescript.py I am reporting the $PATH given by the parent:
currentEnv = os.environ.copy()
print("CHILD:" + currentEnv["PATH"])
My output in the parent terminal is as follows:
PARENT: /usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/local/lib:/home/myusername/bin
In the child window:
CHILD:/sbin:/bin:/usr/sbin:/usr/bin
As a result, I recieve lots of "command not found" errors in the child script when it is calling to any executables found in the parent $PATH.
How can I pass the parent's environment variables down to a child process? I thought this was the default behaviour?
You probably are loosing the environment variables when calling sudo
You can keep your environment variables with sudo by using the -E
switch:
From the manual:
-E, --preserve-env
Indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may
return an error if the user does not have permission to preserve the environment.
So try:
currentEnv =os.environ.copy()
print("PARENT: " + currentEnv["PATH"])
subprocess.Popen(shlex.split("sudo -E gnome-terminal -x bash -c 'python3 somescript.py'"), env=currentEnv)