Set environmental variables in Python

In this tutorial, we are going to learn about setting environmental variables in Python.

Before learning how to set environmental variables in Python we will first learn what are environmental variables in Python.

Environmental Variables:

These are the variables that are similar to dynamic objects. These environmental variables help to know where we have to store the files, where should we store temporary variables, etc.

The setting of environmental variables in Python

In order to set environmental variables in Python, we use theĀ  “OS module”.

Note:

The python’s “environ” dictionary is useful in storing the environment variables available to a program at that moment.

If we want to set environmental variables in Python then it is as simple as setting the values in the dictionary.

For example:

# Setting of environmental variables in Python
os.environ['USER'] = 'aaaa'
os.environ['PASSWORD'] = '*****'

In the above example, we have set the environmental variables known as ‘user’ and ‘password’.

After setting of environmental variables it is necessary to know whether they are set or not for this we follow the below code:

# Getting of environmental variables in Python
USER = os.getenv('USER')
PASSWORD = os.environ.get('PASSWORD')

This code returns the environmental variables that are set by us in the above example.

Output:

USER=aaaa
PASSWORD=*****

Note:

We can use the get() function to get the environmental variable. If the variable is not present then it returns “None”.

Example:

>>> print(os.environ.get('code'))

Output:

None

In the above example, it returned none because there is no environmental variable whose name is ‘code’.

we can also assign a value to return when there is no environmental variable using

>>> print(os.environ.get('code', 'no variable'))

Output:

no variable

In the above example, we get ‘no variable’ as output because we set this value to be returned when the environmental variable is not present.

Note:

if you want to know the existing environmental variables then use:

import os
print(os.environ)

This returns all the environmental variables present in the device.

Finally, I hope that this tutorial helped in understanding how to set environmental variables in Python.

You can also read:

 

Leave a Reply

Your email address will not be published. Required fields are marked *