Useful Python Environment variable examples in a code

This tutorial shows you multiple examples in Python

How do I see all environment variables in Python?

To see all environment variables, Please follow the below steps

  • python os module provides access to all environment variables
  • import the os module into the code
  • call os.environ property that returns a dictionary of key and value pairs
  • Iterated dictionary using for in loop with key and value pair of an object.
  • Print the key and value to the console using print Here is an example
for key, value in os.environ.items():
print('{}: {}'.format(key, value))

It prints

PUBLIC: C:\Users\Public
PYTHON2_HOME: C:\Python36
REGIONCODE: APJ
RUBYOPT: -Eutf-8
SESSIONNAME: Console
SYSTEMDRIVE: C:
SYSTEMROOT: C:\WINDOWS
TEMP: C:\Users\Kiran\AppData\Local\Temp
TMP: C:\Users\Kiran\AppData\Local\Temp

How to check whether the Environment variable exists or not

os.environ returns the dictionary of variables and their values.

To get the value from a dictionary, use dictionary[key].

print(os.environ['PUBLIC'])

It returns the value for the environment variable PUBLIC Output:

C:\Users\Public

In case, if the variable does not exist, It throws KeyError For example, PUBLIC1 is not a valid environment variable and throws KeyError.

Traceback (most recent call last):
File "a:\work\python\test.py", line 7, in <module>
print(os.environ['PUBLIC1'])
File "C:\Python36\lib\os.py", line 669, in **getitem**
raise KeyError(key) from None
KeyError: 'PUBLIC1'

To fix KeyError, dictionary[key] is used in try and except, if the key exists.

if the key not exists, the block inside except is called with KeyError binding

Here is a syntax.

try:
dictionary[key] # called if key exists
except KeyError: # called if key not exists
else: # called if key exists
import os
dict=os.environ

# Check for key exists

try:
result=dict["PUBLIC"]
print("exist",result)
except KeyError:
print("not")

# Check for key exists

try:
result=dict["PUBLIC1"]
print("exist",result)
except KeyError:
print("not")

Another way, use dictonary.get(key) to print the value

print(os.environ.get('PUBLIC'))

How to set Environment variables in Python

sometimes, We need to set Environment variables via python code.

os.envion[key]=value syntax is used to change or set the new value.

if the key exists, update to the new value. else create a key and value pair

Here is an example

import os
os.environ['PUBLIC'] = 'D:\Users\Public'
print(os.environ.get('PUBLIC'))

Output:

C:\Users\Public

How to Check specific environment variable exists?

os.environ returns a dictionary of key and value pairs.

key in dictionary syntax is used to check key exists or not and returns True or False.

It can be used in Bool expression(if-else).

Here is an example

import os

print ('PUBLIC' in os.environ) #True
print ('PUBLIC1' in os.environ) #False

if 'PUBLIC' in os.environ:
    print("Environment variable exists")
else:
    print("Environment variable does not exists")

output:

True
False
Environment variable exists

Conclusion

Learned useful examples of Python Environment variables Show all environment variables Check variable exists or not Set variable to new value