I am testing a simple python script to set an environmental variable by os module but it seems it doesn't work, what is wrong with my code or logic?
webcluster4u@ingestion-jenkins-vm:~$ python
Python 2.7.13 (default, Sep 26 2018, 18:42:22)
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['ENV']='ss'
>>> os.environ.get('ENV')
'ss'
>>> exit()
webcluster4u@ingestion-jenkins-vm:~$ echo $ENV
webcluster4u@ingestion-jenkins-vm:~$
asked Jan 2, 2019 at 12:38
1 Answer 1
There's nothing wrong with your script.
This by design. Your python script runs in a child process which inherits the shell's environment, but does not affect it. Any changes you make to the environment will affect the script's process and it's children if any.
answered Jan 2, 2019 at 12:46
5 Comments
Mahdi
How to make it work? i.e setting the environmental variable by the python script?
Yakov Dan
You could export your variables to a bash script and then run it once your script is finished.
Mahdi
I guess irregardless of python or bash I can not set an environmental variable by scripts due to the point you told here.
Yakov Dan
Not quite. You can execute a bash script in a bash console. That will change the environment for that console. You can prepare that bash script using python.
Mahdi
if I run a python script that run that bash, it can not change the environmental variables!, otherwise can you give me a sample code?
lang-py