Skip to content

Instantly share code, notes, and snippets.

@jourdanrodrigues
Last active July 1, 2019 16:37
Show Gist options
  • Save jourdanrodrigues/20f0e1953ee6bbfe10f62858776c2caf to your computer and use it in GitHub Desktop.
Save jourdanrodrigues/20f0e1953ee6bbfe10f62858776c2caf to your computer and use it in GitHub Desktop.
Light dot env file reader for Python (no need for a module)
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