Last active
March 29, 2025 15:25
-
-
Save SebastianBitsch/a14d17b5160d1e9f44eb6dc971cfa5e3 to your computer and use it in GitHub Desktop.
Read `.env` file to environment in Python
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
# Usage: | |
# load_env(path = ".env") | |
# API_KEY = os.getenv('API_KEY', 'some-secret') | |
import os | |
def load_env(path: str) -> None: | |
""" | |
Function for loading .env file for secret API keys etc. and write them to the global enviroment | |
I have the .env file located in the top ws dir, but could be anywhere. Gets rid of dotenv dependency | |
""" | |
if not os.path.exists(path): | |
print(f"Warning: Couldn't locate ENV file at '{path}', no environment variables will be set") | |
return | |
with open(path, 'r') as fh: | |
vars_dict = dict( | |
tuple(line.replace('\n', '').split('=')) for line in fh.readlines() if not line.startswith('#') | |
) | |
os.environ.update(vars_dict) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment