I need to set some environment variables in the python script, and I want to view the set environment variables from all the other scripts (shell scripts) that Python calls (which will be subprocesses).The value is a number.
If I do os.environ["DEBUSSY"] = 1, it complains that 1 must be a string.I also want to know how to read environment variables in python (later part of the script) once set.
#1st floor
You can access environment variables using the os.environ dictionary.
Now, one of the problems I'm having is if I try to run a batch file that sets environment variables using os.system (at **).The bat * file uses the SET command, then it does not actually set them for the python environment (but for subprocesses created using the os.system function).To actually get the variables set in the python environment, I use the following script:
import re import system import os def setEnvBat(batFilePath, verbose = False): SetEnvPattern = re.compile("set (\w+)(?:=)(.*)$", re.MULTILINE) SetEnvFile = open(batFilePath, "r") SetEnvText = SetEnvFile.read() SetEnvMatchList = re.findall(SetEnvPattern, SetEnvText) for SetEnvMatch in SetEnvMatchList: VarName=SetEnvMatch[0] VarValue=SetEnvMatch[1] if verbose: print "%s=%s"%(VarName,VarValue) os.environ[VarName]=VarValue
#2nd floor
You should assign string values to environment variables.
os.environ["DEBUSSY"] = "1"
If you want to read or print environment variables, use
print os.environ["DEBUSSY"]
This change is only valid for the current process that is assigned the current process and will not permanently change the value.The child process automatically inherits the environment of the parent process.
#3rd floor
os.environ behaves like a python dictionary, so it can perform all the common dictionary operations.In addition to the get and set operations mentioned in the other answers, we can simply check to see if the key exists
Python 3
For python 3, the dictionary uses the in keyword instead of has_key
>>> import os >>> 'HOME' in os.environ # Check an existing env. variable True ...
Python 2
>>> import os >>> os.environ.has_key('HOME') # Check an existing env. variable True >>> os.environ.has_key('FOO') # Check for a non existing variable False >>> os.environ['FOO'] = '1' # Set a new env. variable (String value) >>> os.environ.has_key('FOO') True >>> os.environ.get('FOO') # Retrieve the value '1'
One thing to note when using os.environ is:
Although the child process inherited the environment from the parent process, I recently encountered a problem and made it clear that if there were other scripts updating the environment while running the python script, calling os.environ again would not reflect the latest value.
from File Extract:
This mapping was captured the first time an OS module was imported (usually during Python startup as part of processing site.py).Changes made to the environment after this time will not be reflected in os.environ unless changes are made directly by modifying os.environ.
os.environ.data is a dict object that stores all environment variables and contains all environment values:
>>> type(os.environ.data) # changed to _data since v3.2 (refer comment below) <type 'dict'>
#4th floor
When you use environment variables (add/modify/delete variables), a good practice is to revert to the previous state when the function completes.
You may need to look like this In question Describes something like the modified_environ context manager to restore environment variables.
Classic usage:
with modified_environ(DEBUSSY="1"): call_my_function()
#5th floor
Set variables:
Project allocation method using keys:
import os os.environ['DEBUSSY'] = '1' #Environ Variable must be string not Int
Get or check if it exists,
Since os.environ is an instance, you can try the object approach.
Method 1:
os.environ.get('DEBUSSY') # this is error free method if not will return None by default
Will get'1'as the return value
Method 2:
os.environ['DEBUSSY'] # will throw an key error if not found!
Method 3:
'DEBUSSY' in os.environ # will return Boolean True/False
Method 4:
os.environ.has_key('DEBUSSY') #last 2 methods are Boolean Return so can use for conditional statements