Loads environment variables from the .env file into the process environment. This should be called at the very start of the application.
(project_root=None)
| 130 | return {"token_set": False} |
| 131 | |
| 132 | def load_env(project_root=None): |
| 133 | """ |
| 134 | Loads environment variables from the .env file into the process environment. |
| 135 | This should be called at the very start of the application. |
| 136 | """ |
| 137 | # Determine project root relative to this file's location |
| 138 | if not project_root: |
| 139 | # The script is in the project root |
| 140 | project_root = os.path.dirname(os.path.abspath(__file__)) |
| 141 | |
| 142 | env_path = os.path.join(project_root, '.env') |
| 143 | |
| 144 | if not os.path.exists(env_path): |
| 145 | logger.warning(f"Cannot load environment: .env file not found at {env_path}") |
| 146 | return |
| 147 | |
| 148 | try: |
| 149 | with open(env_path, 'r') as f: |
| 150 | for line in f: |
| 151 | line = line.strip() |
| 152 | if line and not line.startswith('#') and '=' in line: |
| 153 | key, value = line.split('=', 1) |
| 154 | # Don't overwrite existing environment variables |
| 155 | if key not in os.environ: |
| 156 | os.environ[key] = value |
| 157 | logger.info(f"Loaded '{key}' from .env file into process environment.") |
| 158 | logger.info(".env file processed.") |
| 159 | except Exception as e: |
| 160 | logger.error(f"Failed to load .env file at {env_path}: {e}", exc_info=True) |
no test coverage detected