Python os.getenv() Method Example
There are various uses example as os.getenv() method. here we are discussing some generally used examples of os.getenv() those are following.
Use of os.getenv() Method
In this example Python script uses the `os` module to retrieve and print the values of two OS environment variables, ‘HOME’ and ‘JAVA_HOME’, using the `os.getenv()` method. The values are assigned to variables and then printed to the console.
Python3
# import os module import os # Get the value of 'HOME' key = 'HOME' value = os.getenv(key) # Print the value of 'HOME' # environment variable print ( "Value of 'HOME' environment variable :" , value) # Get the value of 'JAVA_HOME' # environment variable key = 'JAVA_HOME' value = os.getenv(key) # Print the value of 'JAVA_HOME' # environment variable print ( "Value of 'JAVA_HOME' environment variable :" , value) |
Value of 'HOME' environment variable : /home/ihritik Value of 'JAVA_HOME' environment variable : /opt/jdk-10.0.1
If key does not exist
In this example Python script utilizes the `os` module to retrieve the value of the ‘home’ OS environment variable using the `os.getenv()` method. The obtained value is then printed to the console with a descriptive message.
Python3
# importing os module import os # Get the value of 'home' # environment variable key = 'home' value = os.getenv(key) # Print the value of 'home' # environment variable print ( "Value of 'home' environment variable :" , value) |
Value of 'home' environment variable : None
Explicitly Specifying Default Parameter
In this example Python OS module uses to get the value of the ‘home’ environment variable. It assigns the value to the variable `value` and prints it, defaulting to “value does not exist” if the variable is not present.
Python3
# importing os module import os # Get the value of 'home' # environment variable key = 'home' value = os.getenv(key, "value does not exist" ) # Print the value of 'home' # environment variable print ( "Value of 'home' environment variable :" , value) |
Value of 'home' environment variable : value does not exist
Python | os.getenv() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python OS env standard utility modules. This module provides a portable way of using operating system-dependent functionality.
os.getenv()
method in Python OS env returns the value of the os environment variable key if it exists otherwise returns the default value.