144 lines
4.9 KiB
Python
144 lines
4.9 KiB
Python
import argparse
|
||
import os
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
from datetime import datetime
|
||
|
||
import webview
|
||
from loguru import logger
|
||
|
||
# 获取当前脚本所在的目录
|
||
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")
|
||
url = f'http://127.0.0.1:{port}/index'
|
||
|
||
|
||
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', '|', 'findstr', fr':{run_port}']
|
||
result = subprocess.run(cmd_netstat, capture_output=True, text=True, shell=True)
|
||
out = result.stdout
|
||
if out:
|
||
arr = re.split(r'\s+', out)
|
||
pid = arr[5]
|
||
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('数据库管理系统', url=url)
|
||
webview.start(debug=True)
|
||
|
||
|
||
if __name__ == '__main__':
|
||
|
||
kill_process_by_port(port)
|
||
delete_old_files(app_log_dir, days=2)
|
||
start()
|
||
time.sleep(10)
|
||
parser = argparse.ArgumentParser()
|
||
parser.add_argument('--startWindow',
|
||
type=lambda x: x.lower() == 'true',
|
||
default=None,
|
||
help='设置为true则打开本地窗口,false或未设置则不执行')
|
||
args = parser.parse_args()
|
||
if args.startWindow:
|
||
open_web()
|
||
else:
|
||
logger.warning(f"请打开浏览器,输入 {url} 访问使用,使用期间,请不用关闭此窗口!")
|
||
while True:
|
||
pass
|