import os import time import elevate from loguru import logger import subprocess import sys from datetime import datetime import re import webview # 获取当前脚本所在的目录 new_java_path = 'D:/database/jdk/bin/java.exe' app_log_dir = 'D:/database/logs' port = 12396 # 构建JDK和JAR的路径 jar_path = os.path.join("datas", "electromagnetic.jar") def ensure_dir(directory): if not os.path.exists(directory): os.makedirs(directory) logger.info(f"目录 {directory} 已创建") else: logger.info(f"目录 {directory} 已存在") def get_resource_path(relative_path): """ 获取资源绝对路径,适用于开发环境和PyInstaller打包后 """ if hasattr(sys, '_MEIPASS'): # 打包后的资源路径:sys._MEIPASS + 相对路径 base_path = sys._MEIPASS else: # 开发环境的基础路径 base_path = os.path.dirname(os.path.abspath(".")) return os.path.join(base_path, relative_path) def delete_old_files(directory, days=2): # 计算时间阈值(当前时间 - days天) threshold_time = time.time() - days * 24 * 60 * 60 deleted_count = 0 try: # 遍历目录中的文件 for filename in os.listdir(directory): filepath = os.path.join(directory, filename) # 确保是文件而不是目录 if os.path.isfile(filepath): try: # 获取文件创建时间(Windows系统) creation_time = os.path.getctime(filepath) # 检查文件是否超过阈值 if creation_time < threshold_time: # 删除文件 os.remove(filepath) deleted_count += 1 logger.info(f"已删除: {filename} (创建时间: {format_time(creation_time)})") except Exception as e: logger.info(f"处理文件 {filename} 时出错: {str(e)}", file=sys.stderr) logger.info(f"\n操作完成!共删除 {deleted_count} 个日志文件。") except Exception as e: logger.info(f"遍历目录时出错: {str(e)}", file=sys.stderr) def format_time(timestamp): """将时间戳格式化为可读字符串""" return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') def start(): try: ensure_dir(app_log_dir) new_jar_path = get_resource_path(jar_path) java_command = [new_java_path, "-Xms4096m", "-Xmx4096m", "-jar", new_jar_path] # 创建新进程组(支持Unix/Windows的进程隔离) creation_flags = subprocess.CREATE_NEW_PROCESS_GROUP # 重定向输出到日志文件 formatted_time = datetime.now().strftime("%Y%m%d%H%M%S") log_file = rf'{app_log_dir}\app_{formatted_time}.log' with open(log_file, "a") as log: process = subprocess.Popen( java_command, stdout=log, stderr=log, start_new_session=True, # 创建新会话 creationflags=creation_flags ) logger.info(f"应用已在后台启动! PID: {process.pid}") logger.info(f"日志输出: {os.path.abspath(log_file)}") except Exception as e: logger.info(f"启动失败: {str(e)}") sys.exit(1) def kill_process_by_port(run_port): # 执行netstat命令获取端口占用信息 cmd_netstat = ['netstat', '-ano', '-p', 'tcp'] result = subprocess.run(cmd_netstat, capture_output=True, text=True, shell=True) # 在输出中查找指定端口 pid = None pattern = fr':{run_port}\s+.*LISTENING\s+(\d+)' match = re.search(pattern, result.stdout) if match: pid = match.group(1) # 如果找到PID则终止进程 if pid: try: subprocess.run(['taskkill', '/F', '/PID', pid], check=True) logger.info(f"已终止占用端口 {run_port} 的进程 (PID: {pid})") except subprocess.CalledProcessError: logger.info(f"终止进程 {pid} 失败 (可能权限不足或进程不存在)") else: logger.info(f"端口 {run_port} 未被占用") def open_web(): webview.settings['ALLOW_DOWNLOADS'] = True webview.settings['OPEN_DEVTOOLS_IN_DEBUG'] = False webview.create_window('数据库管理系统', f'http://127.0.0.1:{port}/index') webview.start(debug=True) if __name__ == '__main__': elevate.elevate() kill_process_by_port(port) delete_old_files(app_log_dir, days=2) start() time.sleep(10) open_web()