No El No El - 4 months ago 12
Linux Question

linux Environment vars permanently added using python

I am trying to update a linux environment variable using a bash script, loaded from a python script

1.- I delete it:

del os.environ['USER']


2.- I run sourced the bash script with commands lib:

status, output = commands.getstatusoutput('. ' + PATH +'/script.sh')


2.1.- status = 0; output = 'Environment var updated'

So.. until here, everything seems to works ok

3.- But when I try to test that the var is alredy updated:

print os.environ['USER']


I get the following output:

KeyError: 'USER'

Answer

os.environ is not your environment, but a representation of it, created when the os module is imported for the first time. According to the documentation some platforms will reflect changes to os.environ in the process's environment. Since you run a subprocess to change the environment, those changes are made to the subprocess, not to the process in which your Python code runs.

There is no way to have changes to a process's environment reflected in its parent process's environment.