To print environment variables using Python, use the os module and get the environment variables from the environ dictionary.
import os
print(os.environ)
When working with operating systems, the ability to view, edit and work with environment variables easily can be valuable.
If you want to see all of the environment variables of a user’s operating system, you can easily print all of the environment variables in Python.
With the Python os module environ dictionary, you can access the environment variables of the operating system.
Then, after accessing the dictionary of environment variables, you can print the dictionary with print().
Below is an example of how to print the operating system environment variables with Python.
import os
print(os.environ)
If you want to print each environment variable out individually, then you can loop over all of the environment variables by looping over the items of the dictionary of environment variables.
items() returns a list of tuples, and you can print out each tuple which represents an environment variable.
Below is an example showing you how to print out each environment variable individually in Python.
import os
for env_var_key_value_pair in os.environ.items():
print(env_var_key_value_pair)
Hopefully this article has been useful for you to learn how to print the environment variables of the computer’s operating system with Python.
Leave a Reply