How to Set Environmental Variables in Python?

Before we learn how to set environmental variables in Python, let’s first define environmental variables in Python.

What are Environmental Variables?

These are variables that are identical to dynamic objects. These environmental variables assist us in determining where we must store files, where we should save temporary variables, and so on.

To change the setup/configuration of the system, environment variables are needed. The output of many Python applications is determined by the settings of specific environment variables. When the environment variables change, the python script must be changed to produce the desired results, which is undesirable. This issue can be resolved by reading and setting the value of the environment variable in the Python script according to the requirements. It avoids the need to manually change the environment variable and makes the code more secure by hiding sensitive data required to set the environment variable, such as API tokens.

Setting Environmental Variables in Python

The “OS module” is used in Python to set environmental variables.

The “environ” dictionary in Python is useful for storing the environment variables that are currently available to a program.

Setting environmental variables in Python is as simple as changing the values in the dictionary.

OS module:

To read the environment variables, the os module will need to be imported. In Python, the os.environ object is used to access the environment variable. Using this object, the programmer can set and retrieve the value of any environment variable. Various methods for reading, checking, and assigning the value of an environment variable can be done.

Setting the Environmental Variables

Approach:

  • Import os module using the import keyword
  • Set the environmental variable ‘username’ using the environ function of the os module.
  • Set the environmental variable ‘password’ using the environ function of the os module.
  • The Exit of the Program.

Below is the implementation:

# Import os module using the import keyword
import os
# Set the environmental variable 'username' using the environ function of the os module
os.environ['Username'] = 'btechgeeks'
# Set the environmental variable 'password' using the environ function of the os module
os.environ['Password'] = '****'

Here, we set the environmental variables ‘Username’ and ‘Password.’

After creating/setting environmental variables, we need to know whether they are set or not. To do so, we use the following code:

Getting the Environmental Variables

# Get the above set environmental variables Username, Password using the
# getenv(), get() functions respectively
Username = os.getenv('Username')
print("Username:", Username)
Password = os.environ.get('Password')
print("Password:", Password)

Output:

Username: btechgeeks
Password: ****

NOTE:

To get the environmental variable, we can use the get() function. If the variable does not exist, it returns “None.”

>>print(os.environ.get('python'))

Output:

None

Printing All the Environmental Variables

# Import os module using the import keyword
import os

# Loop in the environmental variables using the for loop
print("The all environmental variables and its corresponding values:")
for environ_variable in os.environ:
    # Print the all environmental variables and its corresponding values using the
    # environ function of the os module.
    print(environ_variable, '-->', os.environ[environ_variable])

Output:

The all environmental variables and its corresponding values:
CUDNN_VERSION --> 8.0.5.39
LD_LIBRARY_PATH --> /usr/local/nvidia/lib:/usr/local/nvidia/lib64
CLOUDSDK_PYTHON --> python3
LANG --> en_US.UTF-8
HOSTNAME --> 3fbc910cefdc
OLDPWD --> /
CLOUDSDK_CONFIG --> /content/.config
NVIDIA_VISIBLE_DEVICES --> all
DATALAB_SETTINGS_OVERRIDES --> {"kernelManagerProxyPort":6000,"kernelManagerProxyHost":"
172.28.0.3","jupyterArgs":["--ip=\"172.28.0.2\""],"debugAdapterMultiplexerPath":"/usr/local/bin/
dap_multiplexer",
"enableLsp":true}
ENV --> /root/.bashrc
NCCL_VERSION --> 2.7.8
TF_FORCE_GPU_ALLOW_GROWTH --> true
NO_GCE_CHECK --> True
PWD --> /
HOME --> /root
LAST_FORCED_REBUILD --> 20220308
DEBIAN_FRONTEND --> noninteractive
LIBRARY_PATH --> /usr/local/cuda/lib64/stubs
GCE_METADATA_TIMEOUT --> 0
GLIBCPP_FORCE_NEW --> 1
TBE_CREDS_ADDR --> 172.28.0.1:8008
SHELL --> /bin/bash
GCS_READ_CACHE_BLOCK_SIZE_MB --> 16
PYTHONWARNINGS --> ignore:::pip._internal.cli.base_command
CUDA_VERSION --> 11.1.1
NVIDIA_DRIVER_CAPABILITIES --> compute,utility
SHLVL --> 0
PYTHONPATH --> /env/python
NVIDIA_REQUIRE_CUDA --> cuda>=11.1 brand=tesla,driver>=418,driver<419 brand=tesla,driver>
=440,driver<441 brand=tesla,driver>=450,driver<451
TBE_EPHEM_CREDS_ADDR --> 172.28.0.1:8009
COLAB_GPU --> 0
GLIBCXX_FORCE_NEW --> 1
PATH --> /opt/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:
/sbin:/bin:/tools/node/bin:/tools/google-cloud-sdk/bin
LD_PRELOAD --> /usr/lib/x86_64-linux-gnu/libtcmalloc.so.4
JPY_PARENT_PID --> 41
TERM --> xterm-color
CLICOLOR --> 1
PAGER --> cat
GIT_PAGER --> cat
MPLBACKEND --> module://ipykernel.pylab.backend_inline
ENABLE_DIRECTORYPREFETCHER --> 1
USE_AUTH_EPHEM --> 0
PYDEVD_USE_FRAME_EVAL --> NO
Username --> btechgeeks
password --> python
Password --> ****

Printing A Specific Environmental Variable Value

# Print a specific environment variable(HOSTNAME) and its value
print("The value of environment variable HOSTNAME =  ", os.environ['HOSTNAME'])

Output:

The value of environment variable HOSTNAME = 3fbc910cefdc