构建:打包和开发时使用不同的配置文件

This commit is contained in:
li-xiaochen 2024-12-14 12:37:52 +08:00
parent 89c4121f61
commit f604e8ac99
6 changed files with 64 additions and 5 deletions

View file

@ -9,7 +9,7 @@
前端运行 `npm run build` 生成 `ui/dist`,之后安装 PyInstaller,运行
```bash
pyinstaller -w --add-data ui/dist:ui/dist launcher.py
pyinstaller -w --add-data "ui/dist;ui/dist" --add-data "launcher/sys_config/config_dist.yaml" launcher.py
```
在dist文件夹生成launcher文件夹,切到dist文件夹下运行

View file

@ -16,6 +16,7 @@ import webview
from py7zr.callbacks import ExtractCallback
from launcher import config
from launcher.sys_config import sys_config
from log import logger
mimetypes.add_type("text/html", ".html")
@ -344,9 +345,7 @@ class Api:
if Path(upgrade_script_name).exists():
os.remove(upgrade_script_name)
# url = "ui/dist/index.html"
url = "http://localhost:5173/"
window = webview.create_window(
f"mower-ng launcher {version}", url, js_api=Api()
f"mower-ng launcher {version}", sys_config.get('url'), js_api=Api()
)
webview.start()

View file

@ -0,0 +1,54 @@
import sys
import os
import yaml
class SysConfig:
"""
读取系统配置文件
"""
# ui路径
url: str
# 日志输出级别
log_level: str
def __init__(self):
self.config = {}
self.config_path = self.get_config_path()
self.load_config()
def get_config_path(self):
if getattr(sys, 'frozen', False):
# logger.error("打包配置")
# 如果是打包后的可执行文件
base_path = sys._MEIPASS
config_subdir = 'launcher/sys_config' # 添加子目录
config_filename = 'config_dist.yaml'
else:
# logger.error("本地配置")
# 如果是本地开发环境
base_path = os.path.dirname(__file__)
config_subdir = '' # 本地开发环境不需要子目录
config_filename = 'config_local.yaml'
config_path = os.path.join(base_path, config_subdir, config_filename)
return config_path
def load_config(self):
try:
with open(self.config_path, 'r', encoding='utf-8') as file:
self.config = yaml.safe_load(file)
except FileNotFoundError:
pass
# logger.error(f"配置文件未找到: {self.config_path}")
except Exception as e:
pass
# logger.error(f"加载配置文件时出错: {str(e)}")
def get(self, key):
return self.config.get(key)
# 创建一个全局配置实例
sys_config = SysConfig()

View file

@ -0,0 +1,2 @@
url: "ui/dist/index.html"
log_level: "ERROR"

View file

@ -0,0 +1,2 @@
url: "http://localhost:5173/"
log_level: "INFO"

4
log.py
View file

@ -3,11 +3,13 @@ import logging
import sys
from logging.handlers import RotatingFileHandler
log_level = logging.INFO
from launcher.sys_config import sys_config
# 配置日志
def setup_logger():
log_level = sys_config.get('log_level')
logger = logging.getLogger("launcher.log")
logger.setLevel(log_level)