Using environment variables in Python - python

I have an environment variable called %CCDeviceID%. When I run a command using python in Command Prompt, I want to be able to use this variable, and including %CCDeviceID% in the script doesn't work. How can I implement environment variables into my python script?
Thanks
Ed

Use os.environ:
import os
print os.environ['CCDeviceID']

You can get a listing of all environment variables available to you simply by doing the following:
>>> import os
>>> print os.environ
os.environ is a dictionary mapping env variable name to its value
In your case, you probably need to omit the % symbols. To get CCDeviceID.

Related

Access to system variable by using os.environ

I've created Windows system variable using below code:
import os
os.environ['BJT'] = 'HELLO'
But I can't see it in Advanced settings \ system variables Also I can't see it when I try to print it:
import os
print(os.environ['BJT'])
I thought that when I create system variable using os.environ it is created exacly like when I do it in system settings. Is it possible to create system variable from python code and access it even when I restart computer?
You need to call the system (with admin privileges) to create a system variable, you can use subprocess:
import subprocess
subprocess.run(['setx', 'BJT', '"HELLO"', '/M'])
Prior to python3.5 you will need to use process.call instead
There is a misunderstanding with what environment is. It is just a mapping of (string) variables that a process can pass to its children. Specifically a process can change its own environment (which will be used by its future children) but this will not change its parent's environment, nor even the environment of its already existing children if any.
In addition, Windows provides system and user environment variables which are used as the initial environment of any process. This are not changet by os.environ nor by putenv but only from the Windows API or the shell command setx.

Python script running from SCONS cannot access environment variables

Inside of my scons script I execute another python script:
fs = env.Command('fs', None, 'python updatefs.py')
AlwaysBuild(fs)
Depends(fs, main)
In python script I am trying to access an environment variable:
import os
mode = os.environ['PROC_MODE']
The variable was previously set up in the shell:
export PROC_MODE='some_mode'
Python complain:
KeyError: 'PROC_MODE'
What is the proper way to propagate environment to an external script?
This is covered in lightly in the FAQ:
FAQ
Basically SCons constructs a clean reproducible set of environment variables so that differences in any user's environment won't break a build.
So if you want to propagate a particular variable from your shell you can explicitly do it as such:
env['ENV']['MY_VARIABLE']=os.environ['MY_VARIABLE']
If you wanted to progagate all environment variables you'd do this:
env['ENV'] = os.environ
Where env is your Environment()

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

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)
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
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.
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

Changes in environment variables are not reflected in python

trying to install spark, I've some problems when I try to set the system enviroment variables. I modify the PATH using:
“Advanced system settings” → “Environment Variables”
but when I call these variables from python, using the code:
import os
path = os.environ.get('PATH', None)
print(path)
The path that shows python don't have the modifications that I put. Thanks
Any program invoked from the command prompt will be given the environment variables that was at the time the command prompt was invoked.
Therefore, when you modify or add an environment variable you should restart the command prompt (cmd.exe) and then invoke python to see the changes.

Modifying operating system environment variables from Python

I'm using Tesseract OCR and everytime I run a new session it asks for setting the TESSDATA_PREFIX variable,
I do so by running the command export TESSDATA_PREFIX="PATH_TO_FILES"
How can I do it inside the python script i'm running ?
Thanks !
You can do:
import os
os.putenv("TESSDATA_PREFIX", "PATH_TO_FILES")
More info
http://docs.python.org/2/library/os.html#os.putenv
Please try adding to your python:
import os
os.environ["TESSDATA_PREFIX"] = "PATH_TO_FILES"
You could try using os module to set environment variable:
setting:
os.environ['TESSDATA_PREFIX'] = "PATH_TO_FILES"
getting:
pat_to_files = os.environ['TESSDATA_PREFIX']
Such variable will be accessible from the python code but it may not remain accessible for other programs when your python code quits.
If your goal is to set env variable for other program then you could try this recipe:
http://code.activestate.com/recipes/159462-how-to-set-environment-variables/

Categories