How to work with environment variables in Python

Answered
Jan 05, 2026 1565 views 1 answers
36

How do I read environment variables in Python and set default values if they do not exist?

L
Bronze 311 rep

1 Answer

7

Reading environment variables

import os

# Get with default value
database_url = os.getenv('DATABASE_URL', 'sqlite:///db.sqlite3')

# Get (raises KeyError if not exists)
api_key = os.environ['API_KEY']

# Check if exists
if 'DEBUG' in os.environ:
    debug = os.environ['DEBUG'] == 'True'

Using python-dotenv

from dotenv import load_dotenv

# Load from .env file
load_dotenv()

# Now use os.getenv as usual
secret = os.getenv('SECRET_KEY')
O
Answered by omar_linux 1 week, 2 days ago
Platinum 593 rep

Your Answer

You need to be logged in to answer questions.

Log In to Answer

Related Questions

Hot Questions

No hot questions available.