ID : 478
viewed : 143
Tags : PythonPython Environment
91
In this tutorial, we will discuss methods to set and get environment variables in Python.
os.environ[]
Object in PythonThe 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.
os.environ.get()
Function in PythonThe 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.
os.getenv()
Function in PythonThe 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.