PyInstaller打包exe后报ModuleNotFoundError:缺失bub_logger.configs模块
解决方案
1. 显式声明子模块
PyInstaller可能未自动识别bub_logger.configs子模块,在bub_logger/__init__.py中添加如下代码,强制让Python将其视为子模块:
from . import configs
2. 添加PyInstaller钩子文件
在bub_logger目录下创建pyinstaller-hooks文件夹,新建hook-bub_logger.py文件,内容如下:
from PyInstaller.utils.hooks import collect_data_files # 收集configs目录下的所有数据文件 datas = collect_data_files('bub_logger.configs')
然后修改setup.py的package_data配置,将钩子文件也纳入打包范围:
package_data={ "bub_logger": ["configs/*", "pyinstaller-hooks/*"], },
这个钩子会告诉PyInstaller自动收集configs下的配置文件,无需使用者手动添加--add-data参数。
3. 兼容打包环境的资源加载方式
importlib.resources在PyInstaller打包后的单文件exe中可能存在路径识别问题,可以改用pkg_resources(兼容性更好)来读取资源:
import pkg_resources import json import yaml def load_config(config_file): config_data = None for ext in ["json", "yaml", "yml"]: try: # 构造资源路径 resource_path = f"configs/{config_file}.{ext}" # 读取资源内容 config_data = pkg_resources.resource_string(__name__, resource_path).decode('utf-8') if ext == "json": config = json.loads(config_data) else: config = yaml.safe_load(config_data) break except (pkg_resources.DistributionNotFound, FileNotFoundError): continue if config_data is None: raise FileNotFoundError(f"Configuration file {config_file} not found.") return config
4. 验证修改效果
重新安装你的包(pip install -e .),再用PyInstaller打包测试。此时PyInstaller会自动读取钩子文件,将配置文件打包进exe,其他开发者导入模块时无需额外修改打包参数。
内容的提问来源于stack exchange,提问作者Zoorn
相关产品推荐
相关产品推荐

