Load environment variables from .env files in order of precedence
()
| 13 | import mimetypes |
| 14 | |
| 15 | def load_environment(): |
| 16 | """Load environment variables from .env files in order of precedence""" |
| 17 | # Order of precedence: |
| 18 | # 1. System environment variables (already loaded) |
| 19 | # 2. .env.local (user-specific overrides) |
| 20 | # 3. .env (project defaults) |
| 21 | # 4. .env.example (example configuration) |
| 22 | |
| 23 | env_files = ['.env.local', '.env', '.env.example'] |
| 24 | env_loaded = False |
| 25 | |
| 26 | print("Current working directory:", Path('.').absolute(), file=sys.stderr) |
| 27 | print("Looking for environment files:", env_files, file=sys.stderr) |
| 28 | |
| 29 | for env_file in env_files: |
| 30 | env_path = Path('.') / env_file |
| 31 | print(f"Checking {env_path.absolute()}", file=sys.stderr) |
| 32 | if env_path.exists(): |
| 33 | print(f"Found {env_file}, loading variables...", file=sys.stderr) |
| 34 | load_dotenv(dotenv_path=env_path) |
| 35 | env_loaded = True |
| 36 | print(f"Loaded environment variables from {env_file}", file=sys.stderr) |
| 37 | # Print loaded keys (but not values for security) |
| 38 | with open(env_path) as f: |
| 39 | keys = [line.split('=')[0].strip() for line in f if '=' in line and not line.startswith('#')] |
| 40 | print(f"Keys loaded from {env_file}: {keys}", file=sys.stderr) |
| 41 | |
| 42 | if not env_loaded: |
| 43 | print("Warning: No .env files found. Using system environment variables only.", file=sys.stderr) |
| 44 | print("Available system environment variables:", list(os.environ.keys()), file=sys.stderr) |
| 45 | |
| 46 | # Load environment variables at module import |
| 47 | load_environment() |
no outgoing calls