Files
growth_report/config/config.py

78 lines
3.1 KiB
Python

import os
import sys
# 尝试导入 toml 解析库
try:
import tomllib as toml # Python 3.11+
except ImportError:
try:
import tomli as toml # pip install tomli
except ImportError:
print("错误: 缺少 TOML 解析库。请运行: pip install tomli")
sys.exit(1)
def get_main_path():
"""
获取程序运行的根目录
兼容:
1. PyInstaller 打包后的 .exe 环境
2. 开发环境 (假设此脚本在子文件夹中,如 utils/)
"""
if getattr(sys, 'frozen', False):
# --- 情况 A: 打包后的 exe ---
# exe 就在根目录下,直接取 exe 所在目录
return os.path.dirname(sys.executable)
else:
# --- 情况 B: 开发环境 (.py) ---
# 1. 获取当前脚本的绝对路径 (例如: .../MyProject/utils/config_loader.py)
current_file_path = os.path.abspath(__file__)
# 2. 获取当前脚本所在的文件夹 (例如: .../MyProject/utils)
current_dir = os.path.dirname(current_file_path)
# 3. 【关键修改】再往上一层,获取项目根目录 (例如: .../MyProject)
# 如果你的脚本藏得更深,就再套一层 os.path.dirname
project_root = os.path.dirname(current_dir)
return project_root
# ==========================================
# 1. 配置加载 (Config Loader)
# ==========================================
def load_config(config_filename="config.toml"):
"""读取 TOML 配置文件"""
# 1. 先获取正确的根目录
main_dir = get_main_path()
# 2. 拼接配置文件的绝对路径 (防止在不同目录下运行脚本时找不到配置文件)
config_path = os.path.join(main_dir, config_filename)
if not os.path.exists(config_path):
print(f"错误: 在路径 {main_dir} 下找不到配置文件 {config_filename}")
print(f"尝试寻找的完整路径是: {config_path}")
sys.exit(1)
try:
with open(config_path, "rb") as f:
data = toml.load(f)
# 将 TOML 的层级结构映射回扁平结构
# 关键点:所有的 os.path.join 都必须基于 main_dir (项目根目录)
config = {
"root_path": main_dir, # 方便调试,把根目录也存进去
"source_file": os.path.join(main_dir, data["paths"]["source_file"]),
"output_folder": os.path.join(main_dir, data["paths"]["output_folder"]),
"excel_file": os.path.join(main_dir, data["paths"]["excel_file"]),
"image_folder": os.path.join(main_dir, data["paths"]["image_folder"]),
"fonts_dir": os.path.join(main_dir, data["paths"]["fonts_dir"]),
"class_name": data["class_info"]["class_name"],
"teachers": data["class_info"]["teachers"],
"default_comment": data["defaults"].get("default_comment", "暂无评语"),
"age_group": data["defaults"].get("age_group", "大班上学期"),
"ai": data["ai"]
}
return config
except Exception as e:
print(f"读取配置文件出错: {e}")
sys.exit(1)