The os.getenv()
method is used to extract the value of the environment variable key if it exists. Otherwise, the default value will be returned.
Note: The
os
module in Python provides an interface to interact with the operating system.
os.getenv(key, default=None)
This method takes the following values as an argument:
key
: This is the name of an environment variable.
default=None
: If a key does not exist, default
will be set to None
. default
is an optional value.
This method returns a string denoting the value of the environment variable. If it does not exist, it returns the value of the default
parameter.
Let’s see how to use the getenv()
method in the code examples below:
Let’s look at the code below:
import os # importing os module# defining Env variable with 'HOME' as valuekey = "HOME"# invoking getenv() methodvalue = os.getenv(key, default=None)print(f"Value of env variable key='HOME': {value}")
Line 4: We use the 'HOME'
as key.
Line 7: We invoke the os.getenv()
method to extract key
parallel to this value.
The output is a value parallel to the specified key in an environment variable.
Let’s look at the code below:
import os # importing os module# value for env variablekey = 'PYTHON_USR'# invokinig os.getenv() with default= 'python/edpresso'value = os.getenv(key,default='python/edpresso')print(f"Value of 'PYTHON_USR' env variable: {value}")
Line 4: We use key='PYTHON_USR'
for the environment variable to extract its value as a string.
Line 7:
We invoke the getenv()
method with 'PYTHON_USR'
as key and 'python/edpresso'
as the default value.
In the code snippet, the key-value 'PYTHON_USR'
does not exist in the environment variable. Therefore, the default value 'python/edpresso'
is returned.