Python - How To Set and Get Environment Variables in Python

ID : 478

viewed : 143

Tags : PythonPython Environment

vote vote

91

In this tutorial, we will discuss methods to set and get environment variables in Python.

Set Environment Variables With the os.environ[] Object in Python

The provides many OS-related functionalities in Python. The is used to set environment variables. The following code example shows us how we can set environment variables with the os.environ[] object in Python.

import os  os.environ["My Environment"] = "The Best Environment"  print("Environment Variable Set Successfully") 

Output:

Environment Variable Set Successfully 

In the above code, we set the value of the environment variable My Environment to The Best Environment with the os.environ[] object in Python.

Get Environment Variables With the os.environ.get() Function in Python

The os.environ.get() function can be used to get environment variables in Python. The following code example shows us how we can get environment variables with the os.environ.get() function in Python.

import os  os.environ["My Environment"] = "The Best Environment" myenv = os.environ.get("My Environment")  print(myenv) 

Output:

The Best Environment 

In the above code, we first set the value of the environment variable My Environment with the os.environ[] object and then get the value of the environment variable with the os.environ.get() function.

Get Environment Variables With the os.getenv() Function in Python

The returns a string variable that contains the value of the environment variable x. The following code example shows us how we can get environment variables with the os.getenv() function in Python.

import os  os.environ["My Environment"] = "The Best Environment" myenv = os.getenv("My Environment")  print(myenv) 

Output:

The Best Environment 

In the above code, we first set the value of the environment variable My Environment with the os.environ[] object and then get the value of the environment variable with the os.getenv() function.

  • Related HOW TO?