modify 修复build命令打包问题
This commit is contained in:
@@ -1,82 +1,88 @@
|
|||||||
# config_loader.py - 读取config.toml的示例代码
|
# config_loader.py - 读取config.toml的示例代码
|
||||||
|
|
||||||
import toml
|
|
||||||
import os
|
import os
|
||||||
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, Optional
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
|
if sys.version_info >= (3, 11):
|
||||||
|
import tomllib
|
||||||
|
else:
|
||||||
|
import tomli as tomllib
|
||||||
|
|
||||||
|
|
||||||
class ConfigLoader:
|
class ConfigLoader:
|
||||||
"""TOML配置文件加载器"""
|
"""TOML配置文件加载器"""
|
||||||
|
|
||||||
def __init__(self, config_path: Optional[str] = None):
|
def __init__(self, config_path: Optional[str] = None):
|
||||||
"""
|
"""
|
||||||
初始化配置加载器
|
初始化配置加载器
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
config_path: 配置文件路径,如果为None则自动查找
|
config_path: 配置文件路径,如果为None则自动查找
|
||||||
"""
|
"""
|
||||||
if config_path is None:
|
if config_path is None:
|
||||||
# 自动查找配置文件
|
# 自动查找配置文件
|
||||||
config_path = self._find_config_file()
|
config_path = self._find_config_file()
|
||||||
|
|
||||||
self.config_path = Path(config_path)
|
self.config_path = Path(config_path)
|
||||||
self._config: Dict[str, Any] = {}
|
self._config: Dict[str, Any] = {}
|
||||||
self.load()
|
self.load()
|
||||||
|
|
||||||
def _find_config_file(self) -> str:
|
def _find_config_file(self) -> str:
|
||||||
"""自动查找配置文件"""
|
"""自动查找配置文件"""
|
||||||
possible_paths = [
|
possible_paths = [
|
||||||
"config.toml",
|
"config.toml",
|
||||||
"config/config.toml",
|
"config/config.toml",
|
||||||
"~/.config/myapp/config.toml",
|
"~/.config/myapp/config.toml",
|
||||||
"/etc/myapp/config.toml"
|
"/etc/myapp/config.toml",
|
||||||
]
|
]
|
||||||
|
|
||||||
for path in possible_paths:
|
for path in possible_paths:
|
||||||
expanded_path = os.path.expanduser(path)
|
expanded_path = os.path.expanduser(path)
|
||||||
if os.path.exists(expanded_path):
|
if os.path.exists(expanded_path):
|
||||||
return expanded_path
|
return expanded_path
|
||||||
|
|
||||||
raise FileNotFoundError("未找到配置文件")
|
raise FileNotFoundError("未找到配置文件")
|
||||||
|
|
||||||
def load(self) -> None:
|
def load(self) -> None:
|
||||||
"""加载配置文件"""
|
"""加载配置文件"""
|
||||||
if not self.config_path.exists():
|
if not self.config_path.exists():
|
||||||
raise FileNotFoundError(f"配置文件不存在: {self.config_path}")
|
raise FileNotFoundError(f"配置文件不存在: {self.config_path}")
|
||||||
|
|
||||||
with open(self.config_path, 'r', encoding='utf-8') as f:
|
with open(self.config_path, "r", encoding="utf-8") as f:
|
||||||
self._config = toml.load(f)
|
self._config = tomllib.loads(f.read())
|
||||||
|
|
||||||
def get(self, key: str, default: Any = None) -> Any:
|
def get(self, key: str, default: Any = None) -> Any:
|
||||||
"""获取配置值,支持点号分隔的路径"""
|
"""获取配置值,支持点号分隔的路径"""
|
||||||
keys = key.split('.')
|
keys = key.split(".")
|
||||||
value = self._config
|
value = self._config
|
||||||
|
|
||||||
try:
|
try:
|
||||||
for k in keys:
|
for k in keys:
|
||||||
value = value[k]
|
value = value[k]
|
||||||
return value
|
return value
|
||||||
except (KeyError, TypeError):
|
except (KeyError, TypeError):
|
||||||
return default
|
return default
|
||||||
|
|
||||||
def get_section(self, section: str) -> Dict[str, Any]:
|
def get_section(self, section: str) -> Dict[str, Any]:
|
||||||
"""获取整个配置节"""
|
"""获取整个配置节"""
|
||||||
return self._config.get(section, {})
|
return self._config.get(section, {})
|
||||||
|
|
||||||
def reload(self) -> None:
|
def reload(self) -> None:
|
||||||
"""重新加载配置文件"""
|
"""重新加载配置文件"""
|
||||||
self.load()
|
self.load()
|
||||||
|
|
||||||
def __getitem__(self, key: str) -> Any:
|
def __getitem__(self, key: str) -> Any:
|
||||||
"""支持字典式访问"""
|
"""支持字典式访问"""
|
||||||
return self.get(key)
|
return self.get(key)
|
||||||
|
|
||||||
def __contains__(self, key: str) -> bool:
|
def __contains__(self, key: str) -> bool:
|
||||||
"""检查配置是否存在"""
|
"""检查配置是否存在"""
|
||||||
return self.get(key) is not None
|
return self.get(key) is not None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def all(self) -> Dict[str, Any]:
|
def all(self) -> Dict[str, Any]:
|
||||||
"""获取所有配置"""
|
"""获取所有配置"""
|
||||||
return self._config
|
return self._config
|
||||||
|
|
||||||
@@ -1,30 +1,9 @@
|
|||||||
import sys
|
|
||||||
from .config import ConfigLoader
|
from .config import ConfigLoader
|
||||||
import argparse
|
|
||||||
import os
|
import os
|
||||||
from module_bank import PythonToSQLite
|
from module_bank import PythonToSQLite
|
||||||
from typing import Callable
|
from typing import Callable
|
||||||
|
|
||||||
|
key = None
|
||||||
# 检查是否在 PyInstaller 子进程中
|
|
||||||
def is_pyinstaller_child():
|
|
||||||
return len(sys.argv) > 1 and ("_child.py" in sys.argv[0] or sys.argv[1].isdigit())
|
|
||||||
|
|
||||||
|
|
||||||
def parse_args():
|
|
||||||
"""安全的参数解析函数"""
|
|
||||||
if is_pyinstaller_child():
|
|
||||||
# PyInstaller 子进程,使用默认参数
|
|
||||||
return argparse.Namespace(config="config.toml")
|
|
||||||
|
|
||||||
parser = argparse.ArgumentParser(
|
|
||||||
description="{{ cookiecutter.project_name }} 应用启动脚本"
|
|
||||||
)
|
|
||||||
parser.add_argument("--config", default="config.toml", help="配置文件路径")
|
|
||||||
return parser.parse_args()
|
|
||||||
|
|
||||||
|
|
||||||
args = parse_args()
|
|
||||||
|
|
||||||
|
|
||||||
def init_module_bank(config):
|
def init_module_bank(config):
|
||||||
@@ -33,23 +12,21 @@ def init_module_bank(config):
|
|||||||
if os.path.exists(module_path) == False:
|
if os.path.exists(module_path) == False:
|
||||||
raise ValueError(f"模块路径不存在: {module_path}")
|
raise ValueError(f"模块路径不存在: {module_path}")
|
||||||
|
|
||||||
packer_list = [PythonToSQLite(module_path) for module_path in MODULE_BANK_PATH_LIST]
|
packer_list = [
|
||||||
|
PythonToSQLite(module_path, key=key) for module_path in MODULE_BANK_PATH_LIST
|
||||||
|
]
|
||||||
for packer in packer_list:
|
for packer in packer_list:
|
||||||
modules = packer.list_modules()
|
modules = packer.list_modules()
|
||||||
for module in modules:
|
for module in modules:
|
||||||
print(f"{module['module_name']} {'[包]' if module['is_package'] else ''}")
|
print(f"{module['module_name']} {'[包]' if module['is_package'] else ''}")
|
||||||
packer.install_importer()
|
packer.install_importer(key=key)
|
||||||
|
|
||||||
|
|
||||||
def launch(run_fun: Callable[[dict, dict], None], run_mode: str):
|
def launch(run_fun: Callable[[dict, dict], None], run_mode: str):
|
||||||
|
config = ConfigLoader("config.toml")
|
||||||
config = ConfigLoader(args.config)
|
|
||||||
|
|
||||||
# 获取对应运行模式的配置
|
# 获取对应运行模式的配置
|
||||||
default_config = config.get("default", {})
|
default_config = config.get("default", {})
|
||||||
run_mode = default_config.get("env", "development")
|
|
||||||
app_config = config.get(run_mode, {})
|
app_config = config.get(run_mode, {})
|
||||||
if run_mode == "production":
|
|
||||||
init_module_bank(config)
|
|
||||||
|
|
||||||
run_fun(app_config, default_config)
|
run_fun(app_config, default_config)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import sys
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import TypedDict, Literal, Optional, cast
|
from typing import TypedDict, Literal, Optional, cast
|
||||||
|
|
||||||
|
|
||||||
if sys.version_info >= (3, 11):
|
if sys.version_info >= (3, 11):
|
||||||
import tomllib
|
import tomllib
|
||||||
from typing import Required, NotRequired
|
from typing import Required, NotRequired
|
||||||
|
|||||||
Reference in New Issue
Block a user