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