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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Python String Convert to Lowercase Example
- How to Count Number of Elements in a List in Python?
- How to Get Min Value from Python List?
- How to Convert List to Uppercase in Python?
- Python Split String into List of Characters Example
- How to Get the Last Element of a List in Python?
- Python Delete Files with Specific Extension Example
- Python Post Request with Basic Authentication Example
- Python Get File Extension from Filename Example
- Python List All Dates Between Two Dates Example
- How to Compare Two Dates in Python?
- How to Check if Today is Wednesday or not in Python?
- Python Subtract Minutes from DateTime Example
- Python Subtract Hours from Datetime Example