← retour aux snippets

env: parser un fichier .env (minimal, sans dépendances)

Charger des paires clé=valeur depuis un .env simple.

python config #env#dotenv#config

objectif

Charger des paires clé=valeur depuis un .env simple.

code minimal

from pathlib import Path
from tempfile import TemporaryDirectory

def parse_env(text: str):
    env = {}
    for raw in text.splitlines():
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        k, _, v = line.partition("=")
        k = k.strip()
        v = v.strip().strip('"').strip("'")
        env[k] = v
    return env

with TemporaryDirectory() as tmp:
    p = Path(tmp) / ".env"
    p.write_text("API_KEY='abc'\nDEBUG=1\n", encoding="utf-8")
    env = parse_env(p.read_text(encoding="utf-8"))
    print(env["API_KEY"] == "abc" and env["DEBUG"] == "1")  # attendu: True

utilisation

print(True)

variante(s) utile(s)

cfg = parse_env("A=1\n#comment\nB= two\n")
print(cfg["B"] == "two")

notes

  • Ne gère pas l’expansion de variables ni l’échappement avancé.
  • Pour des besoins complets, utilisez python-dotenv.