Last active
July 1, 2019 16:37
-
-
Save jourdanrodrigues/20f0e1953ee6bbfe10f62858776c2caf to your computer and use it in GitHub Desktop.
Light dot env file reader for Python (no need for a module)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import re | |
from typing import List | |
class DotEnvReader: | |
""" | |
Usage: `DotEnvReader('path').read()` | |
""" | |
def __init__(self, path: str): | |
self.path = path | |
def read(self) -> None: | |
try: | |
with open(self.path) as f: | |
content = f.read() | |
except IOError: | |
return | |
for line in content.splitlines(): | |
try: | |
os.environ.setdefault(*self._extract_key_value(line)) | |
except self.InvalidEnvLine: | |
pass | |
def _extract_key_value(self, line: str) -> List[str, str]: | |
match = re.match(r'\A([A-Za-z_0-9]+)=(.*)\Z', re.sub(r'( +)?#(.+)?', '', line)) | |
if not match: | |
raise self.InvalidEnvLine | |
return [os.path.expandvars(value).strip() for value in match.group(1, 2)] | |
class InvalidEnvLine(Exception): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment