Skip to content
Python

Environment Variables

Read and set environment variables.

By EZ4Code Team
envenv-vars

Code

import os
from dotenv import load_dotenv

# Read env variable
db_url = os.getenv("DATABASE_URL", "sqlite:///default.db")
debug = os.getenv("DEBUG", "false").lower() == "true"

# Set env variable
os.environ["APP_MODE"] = "production"

# Load from .env file
load_dotenv()
api_key = os.getenv("API_KEY")

# Check existence
if "SECRET_KEY" not in os.environ:
    raise RuntimeError("Missing SECRET_KEY")

Explanation

Uses os.getenv to read environment variables; python-dotenv loads .env files.

More Python Snippets