Environment Variables in Python – Read, Print, Set

Programming languages rely heavily on environment variables. An environment variable is a dynamic value stored in a system’s environment. It is accessible to all systems and applications in that environment.

Environment variables can be read, printed, and set utilizing the os module in Python. The purpose of this blog post is to explain how to work with Python environment variables. Here are the contents:

  • How to Read Python Environment Variables?
  • How to Print Python Environment Variables?
  • How to Set Python Environment Variables?

How to Read Python Environment Variables?

In Python; you can read environment variables utilizing the “os.environ” dictionary. The “os.environ” dictionary maps environment variable names to their values. To read an environment variable in Python, you can simply access the value using the environment variable name as the key. The following is an example:

Code:

import os
variable = os.environ.get('path')
print(variable)

The “os.environ.get()” method of the “os” module is used to read the environment variable of the specific variable name “path.”

Output:

The output of the above code will be a dictionary containing all the environment variables along with their values.

The value after expanding will look like this:

How to Print Python Environment Variables?

To print the environment variables, the print() function can be used along with the for loop in Python. Here’s an example:

Code:

import os
env_vars = os.environ
for key, value in env_vars.items():
    print(key, "=", value)

The “os.environ” Python mapping object is used to create a dictionary-like object containing all the environment variables that are currently defined. The for loop is used to iterate over each key-value pair in the dictionary and print them out.

Output:

All environment variables are displayed in the above output.

How to Set Python Environment Variables?

In Python, environment variables are set using the os.environ dictionary. Here’s an example:

Code:

import os
os.environ['MY_VAR'] = 'Hello Python'
print('Variable has been Set!')
print(os.environ['MY_VAR'])

The “os.environ” dictionary is used to set an environment variable named “MY_VAR” to the value ‘Hello Python’. As soon as the variable named “MY_VAR” is set, its name can be used to access/call it.

Output:

The new environment variable called “MY_VAR” with the value Hello Python has been set and accessed.

Conclusion

To read, print and set environment variables, the “os.environ.get()” method, os.environ dictionary, is used in Python. In Python, you can read an environment variable’s value by using its name as the key. The environment variables are returned using the print() function. In Python, the “os.environ” dictionary sets environment variables. In this guide, we discussed how to work with Python environment variables in depth.