Python dotenv


Install python-dotenv with pip:

pip install python-dotenv

Set environment variable in .env file:

echo 'KEY=VALUE' > .env

Create script.py:

touch script.py

Find and load .env:

# script.py
from dotenv import find_dotenv, load_dotenv

load_dotenv(find_dotenv())

Get the the environment variable value using os.environ:

# script.py
from os import environ

print(environ.get("KEY"))

The environment variable value is type str.

Run Python script:

python script.py # VALUE

Script

The full Python script:

# script.py
from os import environ
from dotenv import find_dotenv, load_dotenv

load_dotenv(find_dotenv())

print(environ.get("KEY"))

Demo

Repl.it:



Please support this site and join our Discord!