You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyInstaller打包时如何动态导入modules目录下的所有Python类?

PyInstaller打包后动态加载模块失效的优化方案问题

我的项目结构如下:

src
│   main.py 
│
└───modules
    │   __init__.py
    │   module1.py
    │   module2.py
    |   module3.py

为了动态获取modules文件夹下的所有类,我把modules/__init__.py改成了这段代码:

print(__path__)
for loader, name, is_pkg in pkgutil.walk_packages(__path__):
    module = loader.find_module(name).load_module(name)

    for name, value in inspect.getmembers(module):
        if name.startswith('__'):
            continue

        globals()[name] = value
        __all__.append(name)

这段代码直接用Python运行时完全正常,但通过PyInstaller打包为可执行文件后就失效了——__path__指向bundled_app/dist/main/modules,但该路径下实际不存在modules文件夹。

我之前尝试在spec文件中添加data_files来解决问题:

data_files = [
    ('src/modules', 'modules'),
]

但这个方案会强制打包modules目录下的所有Python文件,我想寻求更优的解决方案。

内容的提问来源于stack exchange,提问作者tCot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 01:45:35