How to print os environment variables with Python

23 January,2022 by Rambler

Question: I can print out the os environment variables using  Python with :        

                    import os;

                    print(os.environ);

 

but it prints out all the environment variables without any line breaks. How can I write  a  for loop that will list out all the environment variables one per line in a more readable format

Answer:  This Python for statetment  will  extract every envrionment variable from the os and sort in ascending order through the use of the sorted() function.

import os;

for i, l in sorted(os.environ.items()):     

    print(i+':',l)     

    print('\n')


Author: Rambler (http://www.dba-ninja.com)


Share:

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment on How to print os environment variables with Python


dba-ninja.com