Access environment variable values in Python
Hey geek! in this tutorial we are going to learn how to access environment variable values in Python.
After this tutorial, we will be knowing how to set and use the environment variables.
Generally, we import the os module and go to the environ property for accessing the environment variable values.
Interacting with environment variable values in Python
Let us go through the simple code in Python which will help us in understanding the concept better.
Firstly, let us save the below file.
import os API_KEY = os.environ['API_KEY']
In the above example, we have used the brackets of type [ ] which refers to the set.
So if we run the above code by exporting it to the terminal, we get
export API_KEY=456 filename.py 456
Storing local environment variables
Follow the steps below:
- For Storing the local environment variables we need to install Python decouple in our local Python environment.
$ pip install python-decouple
- After installing the decouple, we can create a .env file in the root of our project, and then we can add up the environment variables.
$ touch .env # create a new .env file $ nano .env # open the file in your text editor
- Then, we can add our respective environment variables.
USER=alex KEY=hfy92kadHgkk29fahjsu3j922v9sjwaucahf
- Now the actual part comes into the picture, that is – accessing the environment variables
from decouple import config API_USERNAME = config('USER') API_KEY = config('KEY')
By using these environment variables we can access confidential information whether it is the username or the password.
So, this is all about accessing the environmental variables in Python.
I hope that you have learned something in this tutorial.
Thank you
Have fun. Keep Learning
Some of the articles that you can refer to on your interest:
Leave a Reply