Populate ``os.environ`` with key/value pairs from a .env file once per process.
(dotenv_path: Path | None = None)
| 9 | |
| 10 | |
| 11 | def load_dotenv_file(dotenv_path: Path | None = None) -> None: |
| 12 | """Populate ``os.environ`` with key/value pairs from a .env file once per process.""" |
| 13 | global _DOTENV_LOADED |
| 14 | if _DOTENV_LOADED: |
| 15 | return |
| 16 | |
| 17 | path = dotenv_path or Path(".env") |
| 18 | if path.exists(): |
| 19 | for line in path.read_text(encoding="utf-8").splitlines(): |
| 20 | stripped = line.strip() |
| 21 | if not stripped or stripped.startswith("#"): |
| 22 | continue |
| 23 | if "=" not in stripped: |
| 24 | continue |
| 25 | key, value = stripped.split("=", 1) |
| 26 | key = key.strip() |
| 27 | value = value.strip().strip('"').strip("'") |
| 28 | os.environ.setdefault(key, value) |
| 29 | |
| 30 | _DOTENV_LOADED = True |
| 31 | |
| 32 | |
| 33 | def build_env_var_map(extra_vars: Dict[str, str] | None = None) -> Dict[str, str]: |
no test coverage detected