Python: Environment Variables not updating

RayJ_inSJ

I am trying to overwrite to environment variables in Python. I can read the value and then write the value and print the updated value. But then if I check the value in command line its still the original value. Why is that?

First, I create the variable

export MYVAR=old_val

My test script myvar.py

#!/usr/bin/env python3
import os
print (os.environ['MYVAR'])
os.environ['MYVAR'] = "new_val"
print (os.environ['MYVAR'])

Outputs

$ ./myvar.py 
old_val
new_val
$ echo $MYVAR
old_val

As you can see, the last line of the output still shows the old_val

gelonida

Short version:

The python script changes its environment. However this does not affect the environment of the parent process (The shell)

Long version:

Well this is a well know, but quite confusing problem.

What you have to know is, that there is not the environment, each process has its own environment.

So in your example above the shell (where you type your code) has one environment. When you call ./myvar.py, a copy of the current environment is created and passed to your python script. Your code 'only' changes this copy of the environment. As soon as the python script is finished this copy is destroyed and the shell will see its initial unmodified environment.

This is true for most operating systems (Windows, Linux, MS-DOS, ...)

In other words: No child process can change the environment of the process, that called it.

In bash there is a trick, where you source a script instead of calling it as a process.

However if your python script starts another process (for example /bin/bash), then the child process would see the modified environment.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related