Python

How to get and set environment variables in Python

Environment variables are used to change the system configuration. The output of the many Python applications depends on the values of the particular environment variables. When those environment variables change, the python script requires changing to get the appropriate output, which is not desirable. This problem can be solved by reading and setting the value of the environment variable in the Python script based on the requirement. It eliminates the task of changing the environment variable manually and makes the code more secure by hiding the sensitive data required to assign the environment variable, such as API token. The ways to set and get the environment variable in Python have shown in this tutorial.

Read Environment Variables in Python:

The os module will require to import to read the environment variables. The os.environ object is used in Python to access the environment variable. The coder can set and get the value of any environment variable by using this object. Different ways to read, check and assign the value of the environment variable have shown in the next part of this tutorial.

Example-1: Read all and specific environment variable

Create a python file with the following script to read and print all variables and the specific environment variable. The ‘for’ loop has used in the script to read and print all existing environment variable names and values. Next, the value of the ‘HOME’ variable has been printed.

# Import os module
import os

# Iterate loop to read and print all environment variables
print("The keys and values of all environment variables:")
for key in os.environ:
    print(key, '=>', os.environ[key])

# Print the value of the particular environment variable
print("The value of HOME is: ", os.environ['HOME'])

Output:

The following output will appear after executing the above script. The list of all environment variables has been printed, and the value of the HOME variable has been printed at the end of the output.

Example-2: Check the specific environment variable is set or not

Create a python file with the following script to check the particular environment variable is set or not. Here, the os module has been used to read the values of the particular environment variable, and the sys module has been used to terminate from the script. The infinite ‘while’ loop has continuously checked the value of the specific environment variable continuously until the user provides a variable name that is not set. If the user provides an environment variable name as input, then the value of that variable will be printed. If the user provides an

# Import os module
import os
# Import sys module
import sys

while True:
    # Take the name of the environment variable
    key_value = input("Enter the key of the environment variable:")

    # Check the taken variable is set or not
    try:
        if os.environ[key_value]:
            print("The value of", key_value, " is ", os.environ[key_value])
    # Raise error if the variable is not set
    except KeyError:
        print(key_value, 'environment variable is not set.')
        # Terminate from the script
        sys.exit(1)

Output:

After executing the above script, the following output will appear if the variable name taken is set for the first input value and not set for the second input value. According to the output, the value of the HOME variable is set, and the value of this variable has been printed. Next, the API_KEY has taken as the variable that is not set. So, the script has terminated after displaying the message.

Example-3: Check the particular environment variable is on or off

Create a python file with the following script to check a particular environment variable is on or off. The get() function has been used in the script to check the current value of the ‘DEBUG’ is True or False. The script will print the message based on the value of the variable.

# Import os module
import os

# Checking the value of the environment variable
if os.environ.get('DEBUG') == 'True':
    print('Debug mode is on')
else:
    print('Debug mode is off')

Output:

The following output will appear after executing the above script if the value of the DEBUG variable is False. The variable’s value can be changed by using the setdefault() function shown in the next example.

Example-3: Assign the value to the environment variable

The setdefault() function is used to set the value of any environment variable. Create a python file with the following script to enable the environment variable, ‘DEBUG’, that is disabled by default. The value of this variable has been enabled at the beginning of the script by setting the value to True using the setdefault() function. Next, the value of this variable has checked by using the get() function. The message, ‘Debug mode is on’ will be printed if the variable is set properly; otherwise, the message, ‘Debug mode is off’ will be printed.

# Import os module
import os

# Set the value DEBUG variable
os.environ.setdefault('DEBUG', 'True')

# Checking the value of the environment variable
if os.environ.get('DEBUG') == 'True':
    print('Debug mode is on')
else:
    print('Debug mode is off')

Output:

The following output will appear after executing the above script. The ‘DEBUG’ variable has been enabled by using setting its value to True. So, the message, ‘Debug mode is on’ has printed as the output.

Conclusion:

The values of the environment variables can be set or get by using environ[] array of the os module or by using the setdefault() and the get() functions. The name of the environment variable is used as the index of the environ[] array to set or get the value of that variable. The get() function is used to get the value of a particular variable, and setdefault() function is used to set the value of the particular variable.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.