Python Set Environment Variable

We can set an environment variable in Python using os module. Python os module environ works as a dictionary that holds the environment variables available to the program at that moment.

Note that the environment variables dictionary gets generated when the os module is loaded, so any further change in the environment variables through other ways, such as export via Terminal, will not be reflected.

Print Current Environment Variables

We can print os.environ variable to learn about the existing environment variables that are available to the program.

Output:

 

Python Current Environment Variable

Check if environment variable exists or not?

We can check if environment variable exists or not using in statement.

Output:

Changing the environment variable value can have serious implications for the execution of the program. Hence, it’s advisable to first check if the environment variable exists or not. Then it’s up to you whether you want to modify the value or not. You can always define a new environment variable and use it in your program.

Python set environment variable

We can set an environment variable like we set the values in the dictionary.

Note that the environment variable key-value pair must be a string, otherwise an error will be raised.

Python Read Environment Variable

Let’s see how to read the environment variable we have set in the above code snippet.

Output: MySQL Version = 5.7.18

But is this the correct way to retrieve environment variable value? Let’s see what happens when the environment variable is not present.

The better way is to use get() function of environ variable. If the environment variable is not present, then it will return None.

We can also specify a default value to return if the environment variable is not present.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: os.environ

By admin

Leave a Reply