Unable to print environmental variable in python which is set manually by the user to use that variable in later part of code

Viewed 2050

I added a environmental variable manually as setx NEWVAR SOMETHING, so that my tool later uses the NEWVAR variable in the script but I am unable to access it, please help. Also below is the code. And for your information I am able to access the predefined system variables

try:  
   kiran=os.environ["NEWVAR"]
   print kiran
except KeyError: 
   print "Please set the environment variable NEWVAR"
   sys.exit(1)
3 Answers

You need to make sure your environment variable is persistent following a restart of your shell otherwise your new environment variable will not be accessible later on

ekavala@elx75030xhv:/var/tmp$ export NEWVAR='alan'
ekavala@elx75030xhv:/var/tmp$ python test.py 
alan
*closes shell and reopens*
ekavala@elx75030xhv:/var/tmp$ python test.py 
Please set the environment variable NEWVAR

Update your $HOME/.bashrc or /etc/environment with the variable instead of just doing a setx or export

Note: If you update /etc/environment you will need to reboot your computer to have the environment variables set in your shell

Instead of using setx to set those environment variables; try using EXPORT. The following example worked for me.

export MYCUSTOMVAR="testing123"
python testing.py

Note: If you are on Windows you can set the env variable with SET.

SET MYCUSTOMVAR=testing123

testing.py

import os

if __name__ == '__main__':
    print("MYCUSTOMVAR: {0}".format(os.environ['MYCUSTOMVAR']))

output

MYCUSTOMVAR: testing123

If you want to set environment variable through script:

import os
os.environ["JAVA_HOME"] = "somepath"

If you set it using command prompt it will be available only for that shell. If you set it in advanced system settings it will available every where but not when you open a new shell inside python script.

Related