Print Environment variables in Python Django

In this Python Django tutorial, we will learn how to print environment variables in dictionaries in Django. We will also discuss the properties of Environment variables.

Environment variables in Python Django

Environment variables are as same as dictionaries, where the environment variable name is the key and the environment variable value, is the value of the key. We can get and set Environment variables in Python using the built-in os module.

We can import this module by using the below code.

import os

How to Print Environment Variables in Python Django?

To print the Environment variables in Python we will use environ property of the Python os module. The environ property is a part of the os module and can be accessed as os.environ and the environ value is set when the python interpreter loads the os module.

Create a file printenvironment.py in VS code and follow the below code.

import os
 
print(os.environ)

With the above command, we will get all the Environment variables printed in our terminal. For better readability, we will add for loop and print the environment variables.

import os
var = os.environ
name = list(var.keys())
path = list(var.values())
for i in range(len(name)):
    print(f'{name[i]} : {path[i]}')

Now we got the Environment variables in the list form with name and key-value pairs. For the reference of output, you will get in your terminal a picture is shown below.

Environment Variables in Python Django
Environment Variables in Python Django

Conclusion

In this Python Django tutorial, we came to know about what Environment variables are and how to print them. We also learned about the use of the os module and environ property to get the dictionary of all the environment variables.

You may also like to read: