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

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


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.


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.


I would use the bash eval statement, and have the python script output the shell code

child.py:

#!/usr/bin/env pythonprint 'FOO="A_Value"'

parent.sh

#!/bin/basheval `./child.py`