Set and Get Environment Variables in Python

  1. Set Environment Variables With the os.environ[] Object in Python
  2. Get Environment Variables With the os.environ.get() Function in Python
  3. Get Environment Variables With the os.getenv() Function in Python

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 os module provides many OS-related functionalities in Python. The os.environ[] object 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 os.getenv(x) function 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.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Environment

  • Access Environment Variables in Python
  • Set Environment Variables in Python
  • dotenv in Python