reformate code

This commit is contained in:
chenxudong 2025-06-12 17:28:58 +08:00
parent 889a677990
commit 6aa87d2739
3 changed files with 37 additions and 14 deletions

View File

@ -17,6 +17,7 @@ def ensure_dir(directory):
else: else:
logger.info(f"目录 {directory} 已存在") logger.info(f"目录 {directory} 已存在")
def get_resource_path(relative_path): def get_resource_path(relative_path):
""" 获取资源绝对路径适用于开发环境和PyInstaller打包后 """ """ 获取资源绝对路径适用于开发环境和PyInstaller打包后 """
if hasattr(sys, '_MEIPASS'): if hasattr(sys, '_MEIPASS'):
@ -27,6 +28,7 @@ def get_resource_path(relative_path):
base_path = os.path.dirname(os.path.abspath(".")) base_path = os.path.dirname(os.path.abspath("."))
return os.path.join(base_path, relative_path) return os.path.join(base_path, relative_path)
def check_service_exist(service_name): def check_service_exist(service_name):
result = subprocess.run(['sc', 'query', service_name], result = subprocess.run(['sc', 'query', service_name],
capture_output=True, text=True) capture_output=True, text=True)
@ -34,6 +36,7 @@ def check_service_exist(service_name):
return False return False
return True return True
def start_service(service_name): def start_service(service_name):
result = subprocess.run(['sc', 'query', service_name], result = subprocess.run(['sc', 'query', service_name],
capture_output=True, text=True) capture_output=True, text=True)
@ -55,11 +58,13 @@ def start_service(service_name):
logger.info(f"启动服务 {service_name} 失败: {start_result.stderr}") logger.info(f"启动服务 {service_name} 失败: {start_result.stderr}")
return False return False
def unzip_file(zip_file_path): def unzip_file(zip_file_path):
new_path = get_resource_path(os.path.join('datas', 'mariadb.zip')) new_path = get_resource_path(os.path.join('datas', 'mariadb.zip'))
with zipfile.ZipFile(str(new_path), 'r') as zip_ref: with zipfile.ZipFile(str(new_path), 'r') as zip_ref:
zip_ref.extractall(zip_file_path) # 将文件解压到指定路径 zip_ref.extractall(zip_file_path) # 将文件解压到指定路径
def start_service_if_not_running(service_name): def start_service_if_not_running(service_name):
result = subprocess.run(['sc', 'query', service_name], result = subprocess.run(['sc', 'query', service_name],
capture_output=True, text=True) capture_output=True, text=True)
@ -87,6 +92,7 @@ class MyCustomError(Exception):
# 调用基类的构造函数 # 调用基类的构造函数
super().__init__(message) super().__init__(message)
class InstallMariaDb: class InstallMariaDb:
def __init__(self): def __init__(self):
@ -118,8 +124,8 @@ class InstallMariaDb:
self.__init_db() self.__init_db()
logger.info("设置Java运行环境") logger.info("设置Java运行环境")
self.__set_java_env() self.__set_java_env()
logger.info("生成脚本文件") # logger.info("生成脚本文件")
self.__set_bat() # self.__set_bat()
logger.info("安装完成10秒后自动退出") logger.info("安装完成10秒后自动退出")
time.sleep(10) time.sleep(10)
pass pass
@ -161,6 +167,7 @@ class InstallMariaDb:
with zipfile.ZipFile(str(new_path), 'r') as zip_ref: with zipfile.ZipFile(str(new_path), 'r') as zip_ref:
zip_ref.extractall(self.root_path) # 将文件解压到指定路径 zip_ref.extractall(self.root_path) # 将文件解压到指定路径
pass pass
# #
# def __set_bat(self): # def __set_bat(self):
# new_path = get_resource_path(os.path.join('datas', 'start.bat')) # new_path = get_resource_path(os.path.join('datas', 'start.bat'))
@ -168,6 +175,7 @@ class InstallMariaDb:
pass pass
class InstallComacDb: class InstallComacDb:
def __init__(self): def __init__(self):
@ -187,6 +195,7 @@ class InstallComacDb:
# Java和JAR文件路径 # Java和JAR文件路径
self.java_path = "D:/database/jdk/bin/java.exe" self.java_path = "D:/database/jdk/bin/java.exe"
ensure_dir(self.app_log_dir) ensure_dir(self.app_log_dir)
pass pass
def start_comac_db(self): def start_comac_db(self):
@ -227,7 +236,6 @@ class InstallComacDb:
except Exception as e: except Exception as e:
logger.info(f"遍历目录时出错: {str(e)}", file=sys.stderr) logger.info(f"遍历目录时出错: {str(e)}", file=sys.stderr)
def __register_and_start_service(self): def __register_and_start_service(self):
# 服务配置 # 服务配置
# 构建NSSM安装命令 # 构建NSSM安装命令
@ -266,6 +274,7 @@ class InstallComacDb:
subprocess.run(rf"net start {self.service_name}") subprocess.run(rf"net start {self.service_name}")
time.sleep(10) time.sleep(10)
if __name__ == '__main__': if __name__ == '__main__':
InstallMariaDb().start_install_mariadb() InstallMariaDb().start_install_mariadb()
InstallComacDb().start_comac_db() InstallComacDb().start_comac_db()

View File

@ -16,8 +16,9 @@ mariadb_data_path = r'D:\database\mariadb\data'
init_sql = r'D:/database/mariadb/data/init.sql' init_sql = r'D:/database/mariadb/data/init.sql'
mariadb_port = 3417 mariadb_port = 3417
init_schema = 'em_data_prod' init_schema = 'em_data_prod'
db_running_port=12396 db_running_port = 12396
db_running_service_name="ComacDataBase" db_running_service_name = "ComacDataBase"
def ensure_dir(directory): def ensure_dir(directory):
if not os.path.exists(directory): if not os.path.exists(directory):
@ -26,11 +27,13 @@ def ensure_dir(directory):
else: else:
loguru.logger.info(f"目录 {directory} 已存在") loguru.logger.info(f"目录 {directory} 已存在")
def unzip_file(): def unzip_file():
new_path = get_resource_path(os.path.join('datas', 'mariadb.zip')) new_path = get_resource_path(os.path.join('datas', 'mariadb.zip'))
with zipfile.ZipFile(str(new_path), 'r') as zip_ref: with zipfile.ZipFile(str(new_path), 'r') as zip_ref:
zip_ref.extractall(root_path) # 将文件解压到指定路径 zip_ref.extractall(root_path) # 将文件解压到指定路径
def register_service(): def register_service():
args1 = root_path + '/mariadb/bin/mysql_install_db.exe' args1 = root_path + '/mariadb/bin/mysql_install_db.exe'
args2 = '--datadir=' + mariadb_data_path args2 = '--datadir=' + mariadb_data_path
@ -41,12 +44,14 @@ def register_service():
loguru.logger.info(res.stdout) loguru.logger.info(res.stdout)
return res return res
def start_mariadb(): def start_mariadb():
command = 'net start ' + service_name command = 'net start ' + service_name
with os.popen(command) as stream: with os.popen(command) as stream:
res = stream.read() res = stream.read()
loguru.logger.info(res) loguru.logger.info(res)
def init_db(): def init_db():
command2 = fr'{root_path}\mariadb\bin\mysql --no-defaults -u root -p{passowrd} -P {mariadb_port} {init_schema} < {init_sql}' command2 = fr'{root_path}\mariadb\bin\mysql --no-defaults -u root -p{passowrd} -P {mariadb_port} {init_schema} < {init_sql}'
with os.popen(command2) as stream: with os.popen(command2) as stream:
@ -55,6 +60,7 @@ def init_db():
os.remove(init_sql) os.remove(init_sql)
pass pass
def init_db_user(): def init_db_user():
new_path = get_resource_path(os.path.join('datas', 'init.sql')) new_path = get_resource_path(os.path.join('datas', 'init.sql'))
shutil.copy(str(new_path), mariadb_data_path) shutil.copy(str(new_path), mariadb_data_path)
@ -63,6 +69,7 @@ def init_db_user():
res = stream.read() res = stream.read()
loguru.logger.info(res) loguru.logger.info(res)
def check_service(): def check_service():
"""检查服务是否存在及运行状态""" """检查服务是否存在及运行状态"""
try: try:
@ -82,6 +89,7 @@ def check_service():
loguru.logger.info(f"检测服务时出错: {str(e)}") loguru.logger.info(f"检测服务时出错: {str(e)}")
return False return False
def get_resource_path(relative_path): def get_resource_path(relative_path):
""" 获取资源绝对路径适用于开发环境和PyInstaller打包后 """ """ 获取资源绝对路径适用于开发环境和PyInstaller打包后 """
if hasattr(sys, '_MEIPASS'): if hasattr(sys, '_MEIPASS'):
@ -92,16 +100,19 @@ def get_resource_path(relative_path):
base_path = os.path.abspath(".") base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path) return os.path.join(base_path, relative_path)
def set_java_env(): def set_java_env():
new_path = get_resource_path(os.path.join('datas', 'jdk.zip')) new_path = get_resource_path(os.path.join('datas', 'jdk.zip'))
with zipfile.ZipFile(str(new_path), 'r') as zip_ref: with zipfile.ZipFile(str(new_path), 'r') as zip_ref:
zip_ref.extractall(root_path) # 将文件解压到指定路径 zip_ref.extractall(root_path) # 将文件解压到指定路径
pass pass
def set_bat(): def set_bat():
new_path = get_resource_path(os.path.join('datas', 'start.bat')) new_path = get_resource_path(os.path.join('datas', 'start.bat'))
shutil.copy(str(new_path), root_path) shutil.copy(str(new_path), root_path)
def start_install(): def start_install():
status = check_service() status = check_service()
if status: if status:
@ -126,6 +137,7 @@ def start_install():
loguru.logger.info("安装完成10秒后自动退出") loguru.logger.info("安装完成10秒后自动退出")
time.sleep(10) time.sleep(10)
def check_service_exists(query_service_name): def check_service_exists(query_service_name):
try: try:
output = subprocess.check_output(['sc', 'query', query_service_name], stderr=subprocess.STDOUT) output = subprocess.check_output(['sc', 'query', query_service_name], stderr=subprocess.STDOUT)
@ -135,16 +147,13 @@ def check_service_exists(query_service_name):
return False return False
raise raise
def start_app():
def start_app():
# 首先检查有没有数据库运行的服务名,如果没有,则需要创建, # 首先检查有没有数据库运行的服务名,如果没有,则需要创建,
pass pass
def kill_process_by_port(run_port): def kill_process_by_port(run_port):
# 执行netstat命令获取端口占用信息 # 执行netstat命令获取端口占用信息
cmd_netstat = ['netstat', '-ano', '|', 'findstr', fr':{run_port}'] cmd_netstat = ['netstat', '-ano', '|', 'findstr', fr':{run_port}']
@ -163,8 +172,6 @@ def kill_process_by_port(run_port):
loguru.logger.info(f"端口 {run_port} 未被占用") loguru.logger.info(f"端口 {run_port} 未被占用")
if __name__ == '__main__': if __name__ == '__main__':
elevate.elevate() elevate.elevate()
start_install() start_install()

View File

@ -18,6 +18,7 @@ port = 12396
jar_path = os.path.join("datas", "electromagnetic.jar") jar_path = os.path.join("datas", "electromagnetic.jar")
url = f'http://127.0.0.1:{port}/index' url = f'http://127.0.0.1:{port}/index'
def ensure_dir(directory): def ensure_dir(directory):
if not os.path.exists(directory): if not os.path.exists(directory):
os.makedirs(directory) os.makedirs(directory)
@ -25,6 +26,7 @@ def ensure_dir(directory):
else: else:
logger.info(f"目录 {directory} 已存在") logger.info(f"目录 {directory} 已存在")
def get_resource_path(relative_path): def get_resource_path(relative_path):
""" 获取资源绝对路径适用于开发环境和PyInstaller打包后 """ """ 获取资源绝对路径适用于开发环境和PyInstaller打包后 """
if hasattr(sys, '_MEIPASS'): if hasattr(sys, '_MEIPASS'):
@ -35,6 +37,7 @@ def get_resource_path(relative_path):
base_path = os.path.dirname(os.path.abspath(".")) base_path = os.path.dirname(os.path.abspath("."))
return os.path.join(base_path, relative_path) return os.path.join(base_path, relative_path)
def delete_old_files(directory, days=2): def delete_old_files(directory, days=2):
# 计算时间阈值(当前时间 - days天 # 计算时间阈值(当前时间 - days天
threshold_time = time.time() - days * 24 * 60 * 60 threshold_time = time.time() - days * 24 * 60 * 60
@ -64,10 +67,12 @@ def delete_old_files(directory, days=2):
except Exception as e: except Exception as e:
logger.info(f"遍历目录时出错: {str(e)}", file=sys.stderr) logger.info(f"遍历目录时出错: {str(e)}", file=sys.stderr)
def format_time(timestamp): def format_time(timestamp):
"""将时间戳格式化为可读字符串""" """将时间戳格式化为可读字符串"""
return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
def start(): def start():
try: try:
ensure_dir(app_log_dir) ensure_dir(app_log_dir)
@ -93,6 +98,7 @@ def start():
logger.info(f"启动失败: {str(e)}") logger.info(f"启动失败: {str(e)}")
sys.exit(1) sys.exit(1)
def kill_process_by_port(run_port): def kill_process_by_port(run_port):
# 执行netstat命令获取端口占用信息 # 执行netstat命令获取端口占用信息
cmd_netstat = ['netstat', '-ano', '|', 'findstr', fr':{run_port}'] cmd_netstat = ['netstat', '-ano', '|', 'findstr', fr':{run_port}']
@ -117,6 +123,7 @@ def open_web():
webview.create_window('数据库管理系统', url=url) webview.create_window('数据库管理系统', url=url)
webview.start(debug=True) webview.start(debug=True)
if __name__ == '__main__': if __name__ == '__main__':
kill_process_by_port(port) kill_process_by_port(port)