|
| 1 | +""" |
| 2 | +MicroPython-dotenv |
| 3 | +A lightweight .env file loader for MicroPython |
| 4 | +~1KB, zero dependencies, memory efficient |
| 5 | +
|
| 6 | +Compatible with ESP32, ESP8266, RP2040, and other MicroPython boards. |
| 7 | +
|
| 8 | +Author: Wesley Fernandes (community contributions welcome) |
| 9 | +License: MIT |
| 10 | +Repository: https://github.com/holdrulff/micropython-dotenv |
| 11 | +""" |
| 12 | + |
| 13 | +__version__ = '1.0.0' |
| 14 | +__all__ = ['get_env', 'load_dotenv'] |
| 15 | + |
| 16 | +# MicroPython doesn't have os.environ, create our own |
| 17 | +_environ = {} |
| 18 | + |
| 19 | + |
| 20 | +def load_dotenv(path='.env'): |
| 21 | + """ |
| 22 | + Load .env file into environment. Returns dict. |
| 23 | +
|
| 24 | + Args: |
| 25 | + path (str): Path to .env file. Default: '.env' |
| 26 | +
|
| 27 | + Returns: |
| 28 | + dict: Dictionary of loaded variables (_environ) |
| 29 | +
|
| 30 | + Example: |
| 31 | + >>> from dotenv import load_dotenv, get_env |
| 32 | + >>> env = load_dotenv('.env') |
| 33 | + >>> wifi_ssid = get_env('WIFI_SSID') |
| 34 | + """ |
| 35 | + global _environ |
| 36 | + try: |
| 37 | + with open(path, 'r') as f: |
| 38 | + for line in f: |
| 39 | + line = line.strip() |
| 40 | + if line and not line.startswith('#') and '=' in line: |
| 41 | + k, v = line.split('=', 1) |
| 42 | + k, v = k.strip(), v.strip() |
| 43 | + # Remove quotes |
| 44 | + if len(v) >= 2 and ((v[0] == '"' == v[-1]) or (v[0] == "'" == v[-1])): |
| 45 | + v = v[1:-1] |
| 46 | + _environ[k] = v |
| 47 | + except Exception as e: |
| 48 | + print("Warning: Could not load .env file:", e) |
| 49 | + return _environ |
| 50 | + |
| 51 | + |
| 52 | +def get_env(key, default=None): |
| 53 | + """ |
| 54 | + Get environment variable with default. |
| 55 | +
|
| 56 | + Args: |
| 57 | + key (str): Environment variable name |
| 58 | + default: Default value if not found. Default: None |
| 59 | +
|
| 60 | + Returns: |
| 61 | + Value of environment variable or default |
| 62 | +
|
| 63 | + Example: |
| 64 | + >>> wifi_ssid = get_env('WIFI_SSID', 'default_network') |
| 65 | + """ |
| 66 | + return _environ.get(key, default) |
0 commit comments