excel-toolkit/scripts/load_env.py

47 lines
1.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
从 .env 文件加载环境变量
"""
import os
from pathlib import Path
def load_env(env_path: Path | None = None) -> None:
"""
从 .env 文件加载环境变量
Args:
env_path: .env 文件路径(默认:当前目录的 .env
"""
if env_path is None:
# 查找 .env 文件
possible_paths = [
Path(".env"),
Path(__file__).parent.parent / ".env",
Path.cwd() / ".env",
]
for p in possible_paths:
if p.exists():
env_path = p
break
if not env_path or not env_path.exists():
return # 没有 .env 文件,跳过
print(f"📄 加载环境变量:{env_path}")
with open(env_path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
# 跳过空行和注释
if not line or line.startswith("#"):
continue
# 解析 KEY=VALUE
if "=" in line:
key, value = line.split("=", 1)
key = key.strip()
value = value.strip()
# 只设置尚未存在的环境变量
if key not in os.environ:
os.environ[key] = value
print(f"{key} = {value[:10]}...")