fs-lawrisk/lawrisk/utils/env_loader.py

37 lines
1.2 KiB
Python
Raw Permalink Normal View History

2025-10-22 19:59:48 +08:00
"""Minimal .env loader to populate os.environ from a .env file.
Supports lines of the form KEY=VALUE, optional quotes, and comments (# ...).
By default, does not override existing environment variables.
"""
from __future__ import annotations
import os
from typing import Optional
def load_env(path: str = ".env", override: bool = False) -> None:
if not os.path.exists(path):
return
try:
with open(path, "r", encoding="utf-8") as f:
for raw in f:
line = raw.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
continue
key, val = line.split("=", 1)
key = key.strip()
val = val.strip()
# Strip quotes if wrapped
if (val.startswith("\"") and val.endswith("\"")) or (
val.startswith("'") and val.endswith("'")
):
val = val[1:-1]
if key and (override or key not in os.environ):
os.environ[key] = val
except Exception:
# Fail silently; callers still can rely on existing env
return