Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change the Environment of a parent process in Python?

Tags:

In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following:

import os os.environ["FOO"] = "A_Value" 

When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way for the python process (or any child process) to modify the environment of its parent process?

I know you typically solve this problem using something like

source script_name.sh 

But this conflicts with other requirements I have.

like image 483
grieve Avatar asked Nov 04 '08 19:11

grieve


People also ask

Can you change environment variables for running process?

It appears to be impossible to modify the environment of a running process unless you attach as a debugger or profiler. It's also a bad idea. Programs are usually designed to check environment variables once and not continually check if they were modified.

Can you set environment variables in Python?

With python code, environment variables can be set and manipulated. Setting the environment variable with code makes it more secure and it does not affect the running python script.

Can a child process change parent process?

Processes have separate memory spaces. One process cannot change the memory of another process, and parent/child processes are no exception. A child cannot change a parent's variables, nor a parent its children's.


2 Answers

No process can change its parent process (or any other existing process' environment).

You can, however, create a new environment by creating a new interactive shell with the modified environment.

You have to spawn a new copy of the shell that uses the upgraded environment and has access to the existing stdin, stdout and stderr, and does its reinitialization dance.

You need to do something like use subprocess.Popen to run /bin/bash -i.

So the original shell runs Python, which runs a new shell. Yes, you have a lot of processes running. No it's not too bad because the original shell and Python aren't really doing anything except waiting for the subshell to finish so they can exit cleanly, also.

like image 77
S.Lott Avatar answered Nov 05 '22 07:11

S.Lott


It's not possible, for any child process, to change the environment of the parent process. The best you can do is to output shell statements to stdout that you then source, or write it to a file that you source in the parent.

like image 41
Martin v. Löwis Avatar answered Nov 05 '22 05:11

Martin v. Löwis