How to Set and Get Environment Variables in Python?
Hello,
Now, let's see an example of how to use environment variable in python. This post will give you a simple example of how to access environment variables in python. let us discuss about how to set and get environment variables in python. let us discuss about python environment variables example. follow the below step for python set and get environment variables.
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.
So, let's see one by one example and use it with python 3 as well.
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
I hope it can help you...