From e851131269562b9563cc4e131b6aaf220ed8862a Mon Sep 17 00:00:00 2001 From: Florez Ospina Juan Felipe Date: Sun, 22 Jun 2025 12:13:14 +0200 Subject: [PATCH] Append new functions to utils/g5505_utils.py. This search for .env file in root directory --- utils/g5505_utils.py | 53 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/utils/g5505_utils.py b/utils/g5505_utils.py index 508cb48..6a9bada 100644 --- a/utils/g5505_utils.py +++ b/utils/g5505_utils.py @@ -450,4 +450,57 @@ def is_structured_array(attr_val): if isinstance(attr_val,np.ndarray): return True if attr_val.dtype.names is not None else False else: + return False + +import os +from pathlib import Path + +def find_env_file(start_path=None): + """ + Find .env file by walking up the directory tree. + Looks for .env in current dir, then parent dirs up to filesystem root. + + Args: + start_path: Starting directory (defaults to current working directory) + + Returns: + Path to .env file or None if not found + """ + if start_path is None: + start_path = os.getcwd() + + current_path = Path(start_path).resolve() + + # Walk up the directory tree + for path in [current_path] + list(current_path.parents): + env_file = path / '.env' + if env_file.exists(): + return str(env_file) + + return None + +import os + +def load_env_from_root(): + """Load environment variables from .env file found in project root or parent.""" + env_file = find_env_file() + + if env_file: + try: + from dotenv import load_dotenv + load_dotenv(env_file, override=True) # override existing values + print(f"Loaded .env from: {env_file}") + return True + except ImportError: + with open(env_file, 'r') as f: + for line in f: + line = line.strip() + if line and not line.startswith('#') and '=' in line: + key, value = line.split('=', 1) + os.environ[key.strip()] = value.strip() + print(f"Manually loaded .env from: {env_file}") + return True + + else: + print("No .env file found in project hierarchy") return False \ No newline at end of file