What is os.getenv() method in Python?

Overview

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.

Syntax


os.getenv(key, default=None)

Parameters

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.

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

Code

Let’s see how to use the getenv() method in the code examples below:

Example 1

Let’s look at the code below:

import os # importing os module
# defining Env variable with 'HOME' as value
key = "HOME"
# invoking getenv() method
value = os.getenv(key, default=None)
print(f"Value of env variable key='HOME': {value}")

Explanation

  • Line 4: We use the 'HOME' as key.

  • Line 7: We invoke the os.getenv() method to extract key parallel to this value.

Output

The output is a value parallel to the specified key in an environment variable.

Example 2

Let’s look at the code below:

import os # importing os module
# value for env variable
key = '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}")

Explanation

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

Output

In the code snippet, the key-value 'PYTHON_USR' does not exist in the environment variable. Therefore, the default value 'python/edpresso' is returned.

Free Resources