Coverage for src/receptiviti/readin_env.py: 94%
18 statements
« prev ^ index » next coverage.py v7.3.2, created at 2024-02-15 16:38 -0700
« prev ^ index » next coverage.py v7.3.2, created at 2024-02-15 16:38 -0700
1"""Read in a environment variables."""
3import os
4import re
7def readin_env(path=".", name=".env", overwrite=False) -> None:
8 """
9 Set environment variables from a .env file.
11 Args:
12 path (str): Path to a .env file, or to a directory containing such a file.
13 By default, this will fall back on `~` then `~/Documents`.
14 name (str): Name of the file, when `path` points to a directory.
15 By default, this will fall back on `.Renviron`.
16 overwrite (bool): If `True`, overwrites existing environment variables with
17 the same name as those in the .env file.
19 Returns:
20 If a file is found, it will add contents to `os.environ`.
21 """
22 path = os.path.expanduser(path)
23 envpath = path if os.path.isfile(path) else path + "/" + name
24 if os.path.isfile(envpath):
25 ql = re.compile("^['\"]|['\"\\s]+$")
26 with open(envpath, encoding="utf-8") as file:
27 for line in file:
28 entry = line.split("=", 1)
29 if len(entry) == 2 and (overwrite or os.getenv(entry[0]) is None):
30 os.environ[entry[0]] = ql.sub("", entry[1])
31 elif name != ".Renviron":
32 readin_env(path, ".Renviron", overwrite)
33 elif os.path.isfile(os.path.expanduser("~/") + name):
34 readin_env("~", name, overwrite)
35 elif os.path.isfile(os.path.expanduser("~/Documents/") + name):
36 readin_env("~/Documents", name, overwrite)