37 lines
1.2 KiB
Python
37 lines
1.2 KiB
Python
|
|
"""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
|
||
|
|
|