excel-toolkit/python_auth_runtime/scripts/load_env.py

91 lines
2.6 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
加载 .env.local .env 文件到环境变量
在具体 skill 中使用
from load_env import load_env
load_env() # 加载 .env.local 或 .env
参考~/clawd/skills/1688-product-master/scripts/run.ts 中的 loadEnvLocal()
"""
import os
from pathlib import Path
def load_env(env_path: Path | None = None) -> bool:
"""
加载 .env.local .env 文件到环境变量
优先级
1. 指定的 env_path
2. 当前目录的 .env.local
3. 当前目录的 .env
4. 父目录的 .env.local
5. 父目录的 .env
Returns:
bool: 是否成功加载
"""
if env_path is None:
# 查找 .env 文件
possible_paths = [
Path.cwd() / ".env.local",
Path.cwd() / ".env",
Path.cwd().parent / ".env.local",
Path.cwd().parent / ".env",
]
for p in possible_paths:
if p.exists():
env_path = p
break
if env_path is None or not env_path.exists():
return False
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
eq_index = line.find("=")
if eq_index <= 0:
continue
key = line[:eq_index].strip()
value = line[eq_index + 1:].strip()
# 去除引号
if (value.startswith('"') and value.endswith('"')) or \
(value.startswith("'") and value.endswith("'")):
value = value[1:-1]
# 只设置尚未存在的环境变量(命令行参数优先级更高)
if key not in os.environ:
os.environ[key] = value
print(f"{key} = {value[:10]}..." if len(str(value)) > 10 else f"{key} = {value}")
return True
if __name__ == "__main__":
import sys
env_file = Path(sys.argv[1]) if len(sys.argv) > 1 else None
if load_env(env_file):
print("\n✅ 环境变量加载成功")
print(f"\n当前环境变量:")
for key in ["CLIENT_KEY", "AUTH_BASE", "AUTH_CACHE_DIR"]:
value = os.getenv(key, "<not set>")
print(f" {key} = {value[:10]}..." if len(str(value)) > 10 else f" {key} = {value}")
else:
print("❌ 未找到 .env 文件")
sys.exit(1)