Python os.getenv() Method Tutorial

The python os module is used to work with the operating systems and related information. The os.getenv() method is used to get and display environment information about the current operating system. The getenv() method can return information like a current shell, current user, JAVA home path, etc. The getenv() method can be used to display specific environment variable values and data.

os.getenv() Method Syntax

The os.getenv() method has very simple syntax like below.

getenv(ENV_KEY)
  • ENV_KEY is used to specify the environment variable key we want to return its value. This parameter is required.

Print Environment Variable Value

In order to print specific environment variable value its key should be provided to the getenv() method as parameter. The environment variable keys generally created as uppercase. In the following example we print the “SHELL” environemtn variable value which stores and returns the current shell path.

import os

print(os.getenv("SHELL"))

In the following output we can see that current system defualt is “/bin/bash”.

'/bin/bash'

If the specified environment variable and key is not defined the None Python value is returned.

import os

print(os.getenv("THISISIMAGINARYVARIABLE"))

The output is like below.

None

Below you can find some environment variable keys which can be used with the getenv() method.

import os

print(os.getenv("SHELL"))

#Print current working directory
print(os.getenv("PWD"))

#Print current user home path
print(os.getenv("HOME"))

#Print current username
print(os.getenv("USERNAME"))

#Print PATH variable content to search binaries and commands
print(os.getenv("PATH"))

Leave a Comment