Skip to content

Instantly share code, notes, and snippets.

@andriika
Created January 23, 2024 01:16
Show Gist options
  • Save andriika/c23c1ea97c600ee583b55b1da05e1f18 to your computer and use it in GitHub Desktop.
Save andriika/c23c1ea97c600ee583b55b1da05e1f18 to your computer and use it in GitHub Desktop.
.env.yaml
import logging
import os
import fsspec
import yaml
from fsspec import AbstractFileSystem
log = logging.getLogger(__name__)
def load_env(path=None):
"""
Load key-value pairs from a .env.yaml file and set them as environment variables.
The idea is similar to https://pypi.org/project/python-dotenv, but use yaml standard.
for defining and processing an env file.
By default, it tries to load .env.yaml file in the current directory.
However, file location can be customized with ENV_FILE environment variable.
Variables defined in a .env.yaml file do NOT override existing environment variables.
"""
if not path:
path = os.environ.get("ENV_FILE", ".env.yaml")
fs, path = fsspec.core.url_to_fs(path)
fs: AbstractFileSystem
if not fs.exists(path):
return
log.info("load env file: %s", path)
with fsspec.open(path, mode="rb") as f:
env: dict = yaml.safe_load(f)
for k, v in env.items():
if k not in os.environ:
log.info(" %s: %s", k, v)
os.environ[k] = v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment