Python Program to Access Environment Variables

Python provides a number of built-in modules and functions for commonly needed programming tasks. For example, to access operating system properties, python provides the module os. You can use the environ object of os module to access operating system environment variables.

The object os.environ behaves like a dictionary of environment variable names and its values. The following python program prints all the environment variables and its values when it is run,

import os

env_obj = os.environ
for x in env_obj:
    print(x,env_obj[x],sep=' => ')

If you want to get the value of an environment variable and if it doesn’t exist, a default value, you can use the getenv() method of os module,

temp_dir = os.getenv('TMPDIR','defaultvalue')
print(temp_dir)

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply