Skip to content

Instantly share code, notes, and snippets.

@lbenitez000
Last active May 2, 2024 02:11
Show Gist options
  • Save lbenitez000/b3b59f7e7ef1c9d119896864d422b7da to your computer and use it in GitHub Desktop.
Save lbenitez000/b3b59f7e7ef1c9d119896864d422b7da to your computer and use it in GitHub Desktop.
Loads environment variables from a .envrc or .env file into os.environ. Also useful to load .env environment variables into PyCharm's Python Console
# Loads environment variables from a .envrc or .env file into os.environ
# Also useful to load .env environment variables into PyCharm's Python Console
# Usage: Download this file into your project's directory and add the following snippet
# to the Python Console's Starting Script.
# Settings > Build, Execution, Deployment > Console > Python Console > Starting script
# ```
# from env_loader import load
# load(".env")
# del load
# ```
# Alternatively, you can add the snippet directly to the Starting Script, but you will
# have to `del` all the variables created by the snippet afterward.
import os
import re
# REGEX_ENVIRONMENT_VARIABLES matches lines that set environment variables
REGEX_ENVIRONMENT_VARIABLES = re.compile(r"^(?:export)?\s+(\w+)=(.*)$")
# REGEX_INTERPOLATION matches values with interpolations in the form ${VAR}
REGEX_INTERPOLATION = re.compile(r"(\$\{(\w+)\})")
def load(filepath: str, echo: bool = False):
with open(filepath, "r") as the_file:
for line in the_file:
match = REGEX_ENVIRONMENT_VARIABLES.match(line)
if match:
key, value = match.groups()
value = value.strip("\"'")
interpolations = REGEX_INTERPOLATION.findall(value)
for interpolation_match, interpolation_key in interpolations:
if interpolation_key not in os.environ:
raise Exception(
f"Variable {interpolation_key} is used, but not defined"
)
value = value.replace(
interpolation_match, os.environ[interpolation_key]
)
if echo:
print(f"{key}={value}")
os.environ[key] = value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment