Coverage for src/receptiviti/readin_env.py: 94%
18 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-12-01 10:33 -0500
« prev ^ index » next coverage.py v7.6.1, created at 2024-12-01 10:33 -0500
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 Examples:
20 ```
21 receptiviti.readin_env()
22 ```
24 Returns:
25 If a file is found, it will add contents to `os.environ`.
26 """
27 path = os.path.expanduser(path)
28 envpath = path if os.path.isfile(path) else path + "/" + name
29 if os.path.isfile(envpath):
30 ql = re.compile("^['\"]|['\"\\s]+$")
31 with open(envpath, encoding="utf-8") as file:
32 for line in file:
33 entry = line.split("=", 1)
34 if len(entry) == 2 and (overwrite or os.getenv(entry[0]) is None):
35 os.environ[entry[0]] = ql.sub("", entry[1])
36 elif name != ".Renviron":
37 readin_env(path, ".Renviron", overwrite)
38 elif os.path.isfile(os.path.expanduser("~/") + name):
39 readin_env("~", name, overwrite)
40 elif os.path.isfile(os.path.expanduser("~/Documents/") + name):
41 readin_env("~/Documents", name, overwrite)