Register Login

How to Set environment variables in Python

Environment variables are variables that define the system configuration and affect the running process and OS environment. Changing the environment variable affects the running process.

With python code, environment variables can be set and manipulated. Setting the environment variable with code makes it more secure and it does not affect the running python script.

Set environment variable:

There are many ways to set environment variables in python.  Some of them are:

  1. With the help of os.environ variable
  2. With the help of os.setdefault variable

These are present in the os module of python.

Environ and set default:

  1. With the environ dictionary variable value of the environment variable can be set by passing the key in the dictionary and assigning the value to it.
  2. With setdefault a default value can be assigned to the environment variable. Bypassing the key and the default value in the setdefault method.

Syntax:

os.environ[key] =  value
os.environ.setdefault[key] = value

Program:

import os
os.environ['USER_1'] = 'username'
os.environ.setdefault('USER_2', 'True')

Explanation:

Here, first we have to import the os module. With os.environ[] bypassing the key as USER_1 sets the value of the environment variable as username. With os.environ.setdefault() set the default value to USER_2.

Get environment variable:

There are many methods in Python to get the environment variable in python. Some of them  are

  1. With os. getenv
  2. With os. get
  3. With os. environ
  4. With for loop

These methods are present in the os module of python.

Getenv, get , environ:

  1. With the getenv method, the value of the environment variable can be obtained by passing the key in the method.
  2. Get method is the same as the getenv in functionality.
  3. Environ is a dictionary-based variable that returns the value of the environment variable on passing the environment key.
  4. Getenv and get do not raise an exception but return None whereas Environ raises an exception if the environment variable does not exist.

Program:

import os
user = os.getenv('USER_1')
password = os.environ.get('USER_3'')
user2  = os.environ['USER_2'] 

Explanation:

Here, first have to import the os module. With the os.getenv() method, get the value of key USER_1 bypassing the key in the method. With os.environ.get() fetches the value of user_3 bypassing the key in the method. With os.environ fetches the value of user_2 bypassing the key as a dictionary key.

With for loop:

With for loop and os.environ, all the key values pair can be read by Iterate overall pair of the key in os.environ and with the key get the value.

Program:

import os
for key in os.environ:
    print(os.environ[key])

Explanation:

Here, first import the os module. With the for loop Iterate over all the keys in the os.environ dictionary variable and at last print the values of the key with the os.environ.

Some use cases of environment variable:

There are many use cases for setting and getting environment variables in python. Some of them which are the most common areas

  1. Environment Variable set or not
  2. Environment Variable on or off

Variable set or not:

With os. environ dictionary-based variables it is possible to check whether an environment variable is a set or not. It returns None if the value is not set else returns the value.

Program:

import os
    try:
        if os.environ['USER_1']:
            print(os.environ['USER_1'])
    except KeyError:
        print('variable is not set.')

Explanation:

Here, First import the os module. Try checking whether the variable is set or not with if and os.environ. if the value is set then print the values of the key else raise an error.

Variable on or off:

With the os.get() function, it is possible to check where the environment variable is on or off.

Program:

Program:
import os
if os.environ.get('USER'') == 'True':
    print('USER is on')
else:
    print('USER is off')

Explanation:

Here, first we have to import the os module.  With if and os.environ.get check whether the environment variables are on or off.

Conclusion:

In this module, we learn about environment variables, ways to set environment variables, ways to get environment variables and some use cases of environment variables. Setting the environment variable with python code makes the environment variable more secure and robust.