重构拆分设备连接/配置
This commit is contained in:
90
app/config_io.py
Normal file
90
app/config_io.py
Normal file
@@ -0,0 +1,90 @@
|
||||
"""配置文件 I/O(Step 4 重构)。
|
||||
|
||||
从 pqAutomationApp.PQAutomationApp 中搬迁。每个函数第一行 `self = app`
|
||||
以保留原有 `self.xxx` 属性访问不变。
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
def get_config_path(app):
|
||||
"""获取配置文件的完整路径(兼容打包后的程序)"""
|
||||
self = app
|
||||
import os
|
||||
import sys
|
||||
|
||||
# 判断是否是打包后的程序
|
||||
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(app):
|
||||
"""加载PQ配置(兼容打包后的程序)"""
|
||||
self = app
|
||||
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(app):
|
||||
"""保存PQ配置(兼容打包后的程序)"""
|
||||
self = app
|
||||
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(app):
|
||||
"""清理配置文件(兼容打包后的程序)"""
|
||||
self = app
|
||||
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)}")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user