Python Set and Get Environment Variables Tutorial Example

23-May-2023

.

Admin

Python Set and Get Environment Variables Tutorial Example

Hi Dev,

Here, I will show you Python set and get environment variables tutorial example. it's a simple example of how to use environment variables in Python. this example will help you how to access environment variables in python. you'll learn how to set and get environment variables in Python. You just need to do some steps to do the python environment variables example.

There are some ways to get and get environment variables in Python. I will give you two examples to get and set env variables in Python. In the First Example, we will simply use export to set the variable and then we will use os library to get the variable value. In the Second Example, we will use python-dotenv library to get and set environment variables.

Example 1:


Here, we will run following command to set "API_KEY_EXAMPLE" variable with value.

export API_KEY_EXAMPLE='Example Python'

Now, we will create main.py file and get "API_KEY_EXAMPLE" variable value as like the below code:

main.py

import os

# Getting environment variable value in Python

apiKeyExample1 = os.environ.get("API_KEY_EXAMPLE")

apiKeyExample2 = os.environ["API_KEY_EXAMPLE"]

print(apiKeyExample1)

print(apiKeyExample2)

Output:

Example Python

Example Python

Example 2:

Install python-dotenv

we need to install python-dotenv library to create custom .env file. so, let us run the below command:

pip3 install python-dotenv

Create Env File with Variables

Add new variable to .env file and add new "API_KEY_EXAMPLE" variable.

.env

API_KEY_EXAMPLE='Example Python nice'

Now, we will create main.py file and get "API_KEY_EXAMPLE" variable value as like the below code:

main.py

import os

from dotenv import load_dotenv

load_dotenv('.env')

apiKeyExample = os.environ["API_KEY_EXAMPLE"]

print(apiKeyExample)

Output:

Example Python nice

#Python