22
loading...
This website collects cookies to deliver better user experience
Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ["STAGE"] = "DEVELOPMENT"
os.environ.get()
method. This retrieves the value of an environment variable currently set on your system. >>> os.environ.get('STAGE')
'DEVELOPMENT'
>>> os.environ
os.environ.pop()
with the key and if you need to clear all environment variables you can use os.environ.clear()
>>> os.environ.pop("STAGE")
'DEVELOPMENT'
>>> os.environ.clear()
clear()
method if you are confident that you do not need any of the environment variables in a program anymore. Using the pop()
method is preferred because it is more specific.os.environ
doesn’t overwrite the environment variables system-wide. If you need to permanently delete or set environment variables you will need to do so with a shell environment, such as Bash.>>> pip install python-dotenv
>>> touch .env
STAGE=DEVELOPMENT
USER=ASHUTOSH
from dotenv import load_dotenv
load_dotenv() # take environment variables from .env file
load_dotenv()
method from the dotenv library and executes it. This will read all the variables in our .env file into our environment.import os
user = os.environ.get('USER')
stage = os.environ.get('STAGE')
print(user, stage)
ASHUTOSH DEVELOPMENT
. Our USER and STAGE was set inside our .env file. The load_dotenv()
method loaded our environment variables and made them accessible using the os.environ method.python-decouple
. We can set the environment variables in a .env file in the same way we did before.>>> pip install python-decouple
.env
file, you can access them in your Python code like this:from decouple import config
user = config('USER')
stage = config('STAGE')
print(user, stage)
ASHUTOSH DEVELOPMENT
. Notice that here we didn't need the os module to access the environment variables..env
to your .gitignore
file so that you don’t commit this file to your code repository.