85 lines
2.9 KiB
Python
85 lines
2.9 KiB
Python
"""配置文件 I/O(Step 4 重构)。
|
||
|
||
从 pqAutomationApp.PQAutomationApp 中搬迁。每个函数第一行 `self = app`
|
||
以保留原有 `self.xxx` 属性访问不变。
|
||
"""
|
||
|
||
import json
|
||
import os
|
||
import sys
|
||
|
||
def get_config_path(self):
|
||
"""获取配置文件的完整路径(兼容打包后的程序)"""
|
||
|
||
# 判断是否是打包后的程序
|
||
if getattr(sys, "frozen", False):
|
||
# 打包后:使用可执行文件所在目录
|
||
base_path = os.path.dirname(sys.executable)
|
||
else:
|
||
# 开发环境:使用项目根目录(app/config_io.py 的上两级 = 工程根)
|
||
base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||
|
||
# 构建配置文件路径
|
||
config_dir = os.path.join(base_path, "settings")
|
||
config_file = os.path.join(config_dir, "pq_config.json")
|
||
|
||
# 确保 settings 目录存在
|
||
if not os.path.exists(config_dir):
|
||
os.makedirs(config_dir)
|
||
|
||
return config_file
|
||
|
||
|
||
def load_pq_config(self):
|
||
"""加载PQ配置(兼容打包后的程序)"""
|
||
try:
|
||
# 使用 self.config_file(已经是动态路径)
|
||
if os.path.exists(self.config_file):
|
||
with open(self.config_file, "r", encoding="utf-8") as f:
|
||
config_dict = json.load(f)
|
||
self.config.from_dict(config_dict)
|
||
if hasattr(self, "log_gui"):
|
||
self.log_gui.log("配置文件加载成功", level="success")
|
||
else:
|
||
if hasattr(self, "log_gui"):
|
||
self.log_gui.log("配置文件不存在,使用默认配置", level="error")
|
||
except Exception as e:
|
||
if hasattr(self, "log_gui"):
|
||
self.log_gui.log(f"加载配置文件失败: {str(e)},使用默认配置", level="error")
|
||
|
||
|
||
def save_pq_config(self):
|
||
"""保存PQ配置(兼容打包后的程序)"""
|
||
try:
|
||
# 确保目录存在
|
||
os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
|
||
|
||
# 保存配置
|
||
self.config.save_to_file(self.config_file)
|
||
except Exception as e:
|
||
if hasattr(self, "log_gui"):
|
||
self.log_gui.log(f"保存配置文件失败: {str(e)}", level="error")
|
||
|
||
|
||
def clear_config_file(self):
|
||
"""清理配置文件(兼容打包后的程序)"""
|
||
from tkinter import messagebox
|
||
|
||
config_file = self.get_config_path()
|
||
|
||
try:
|
||
if os.path.exists(config_file):
|
||
os.remove(config_file)
|
||
self.config_cleared = True
|
||
messagebox.showinfo("提示", "清理成功")
|
||
self.log_gui.log("配置文件清理成功", level="success")
|
||
else:
|
||
messagebox.showinfo("提示", "配置文件不存在")
|
||
self.log_gui.log("配置文件不存在", level="error")
|
||
|
||
except Exception as e:
|
||
messagebox.showerror("错误", "[Error] 清理失败")
|
||
self.log_gui.log(f"[Error] 配置文件清理失败: {str(e)}", level="error")
|
||
|
||
|