继续尝试修复环境变量问题

This commit is contained in:
2026-07-31 22:47:42 +08:00
parent 4dd658c0a7
commit 2629b696c2
3 changed files with 78 additions and 15 deletions
+12 -2
View File
@@ -15,14 +15,24 @@ from pathlib import Path
from urllib.parse import quote_plus
# 加载 .env 文件中的环境变量
_LOADED = False
try:
from dotenv import load_dotenv
env_path = Path(__file__).parent / ".env"
# 使用 resolve() 获取绝对路径,避免 os.chdir() 改变工作目录后 __file__ 变为相对路径
env_path = Path(__file__).resolve().parent / ".env"
# 如果 resolve 后的路径不存在,尝试从当前文件所在目录查找
if not env_path.exists():
# 备用方案:也检查 Notebook 的当前工作目录
cwd_path = Path.cwd() / ".env"
if cwd_path.exists():
env_path = cwd_path
if env_path.exists():
load_dotenv(dotenv_path=env_path, override=True)
print(f"✓ 已加载环境变量文件: {env_path}")
_LOADED = True
else:
print(f"⚠ 未找到 .env 文件: {env_path}")
print(f"⚠ 未找到 .env 文件。检查路径: {Path(__file__).resolve().parent / '.env'}, 当前目录: {Path.cwd() / '.env'}")
except ImportError:
print("⚠ python-dotenv 未安装,无法自动加载 .env 文件。请手动设置环境变量或执行: pip install python-dotenv")