Access environment variable values in Python
An environment variable is a variable that is created by the Operating System. Environment variables are created in the form of Key-Value pairs. To Access environment variable in Python’s we can use os module which provides a property called environ that contains environment variables in key-value pairs. These are the different ways of accessing environment variables:
Access all environment variables using os.environ
Here, we are accessing all the environment variables that are present in the environment.
Access single environment variable using os.environ
Here, we are extracting single environment variable of COMPUTERNAME from the above list. If we try to access an environment variable that is not available we will get KeyError.
Get value of the environment variable key using os.environ
Here, we are extracting single environment variable key of USERPROFILE path from the environ list. This will return None if the given key is not found.
Return default value if the key doesn’t exist
Please Login to comment...