get all environment variables python 1

get all environment variables python

""" lists environment variables, and splits elements in path variable """
import os


for k, v in sorted(os.environ.items()):
    print(k+':', v)
print('\n')
# list elements in path environment variable
[print(item) for item in os.environ['PATH'].split(';')]

Here is what the above code is Doing:
1. The os.environ object is a mapping object that represents all of the environment variables available to the program at that moment.
2. The items() method of this mapping object returns a sequence of (key, value) pairs, which is perfect for iteration.
3. The sorted() function returns a sorted list of the dictionary’s keys, which is used to control the order of the key-value pairs.
4. The for loop iterates over the sorted list of keys.
5. The key is used to index os.environ to get the corresponding value.
6. The print() function displays the key-value pair.

Similar Posts