Files
pqAutomationApp/app/config_io.py

85 lines
2.8 KiB
Python
Raw Normal View History

2026-04-20 10:54:47 +08:00
"""配置文件 I/OStep 4 重构)。
pqAutomationApp.PQAutomationApp 中搬迁每个函数第一行 `self = app`
以保留原有 `self.xxx` 属性访问不变
"""
import json
import os
import sys
def get_config_path(self):
2026-04-20 10:54:47 +08:00
"""获取配置文件的完整路径(兼容打包后的程序)"""
# 判断是否是打包后的程序
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):
2026-04-20 10:54:47 +08:00
"""加载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("✓ 配置文件加载成功")
else:
if hasattr(self, "log_gui"):
self.log_gui.log("⚠️ 配置文件不存在,使用默认配置")
except Exception as e:
if hasattr(self, "log_gui"):
self.log_gui.log(f"⚠️ 加载配置文件失败: {str(e)},使用默认配置")
def save_pq_config(self):
2026-04-20 10:54:47 +08:00
"""保存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)}")
def clear_config_file(self):
2026-04-20 10:54:47 +08:00
"""清理配置文件(兼容打包后的程序)"""
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("✓ 配置文件清理成功")
else:
messagebox.showinfo("提示", "配置文件不存在")
self.log_gui.log("⚠️ 配置文件不存在")
except Exception as e:
messagebox.showerror("错误", "❌ 清理失败")
self.log_gui.log(f"❌ 配置文件清理失败: {str(e)}")