Skip to content

Commit 17f3d35

Browse files
committed
python-ecosys/dotenv: Add .env file loader package.
Signed-off-by: holdrulff <holdrulff@gmail.com>
1 parent d0511a4 commit 17f3d35

File tree

3 files changed

+92
-0
lines changed

3 files changed

+92
-0
lines changed

python-ecosys/dotenv/README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# dotenv
2+
3+
Lightweight .env file loader for MicroPython.
4+
5+
## Installation
6+
7+
```python
8+
import mip
9+
mip.install("dotenv")\
10+
```
11+
12+
## Usage
13+
14+
```
15+
from dotenv import load_dotenv, get_env
16+
17+
load_dotenv('.env')
18+
wifi_ssid = get_env('WIFI_SSID')
19+
```
20+
Full documentation: https://github.com/Holdrulff/micropython-dotenv

python-ecosys/dotenv/manifest.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
metadata(
2+
description="Lightweight .env file loader for MicroPython",
3+
version="1.0.0",
4+
)
5+
6+
package("dotenv")
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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

Comments
 (0)