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

使用PyInstaller打包tflite runtime时出现ModuleNotFoundError求助

解决PyInstaller打包tflite_runtime时的ModuleNotFoundError问题

我之前打包依赖tflite_runtime的脚本时也踩过这个坑!明明本地运行正常,打包后就报找不到tensorflow模块,哪怕加了tflite_runtime到hiddenimports也没用。这是因为tflite_runtime内部的一些代码会隐式引用tensorflow相关的命名空间,但我们又不想引入完整的tensorflow包来增大体积,下面是几个亲测有效的解决方法:

1. 检查并规范代码中的导入方式

首先确保你的代码里完全没有直接导入tensorflow的语句,所有tflite相关的操作都用tflite_runtime的导入:

# 正确的导入方式
import tflite_runtime.interpreter as tflite

如果代码里有任何诸如import tensorflow或者from tensorflow import xxx的语句,哪怕是测试代码残留,都要删掉,否则PyInstaller会自动去寻找tensorflow依赖。

2. 扩展hiddenimports到深层子模块

只添加tflite_runtime到hiddenimports是不够的,PyInstaller可能没检测到它的深层子模块依赖。建议在打包配置里加上这些更具体的模块:

  • 如果用命令行打包,加上参数:
pyinstaller --hidden-import tflite_runtime --hidden-import tflite_runtime.interpreter --hidden-import tflite_runtime.interpreter._interpreter your_script.py
  • 如果用.spec文件,修改Analysis部分的hiddenimports列表:
a = Analysis(
    ['your_script.py'],
    # ...其他配置
    hiddenimports=['tflite_runtime', 'tflite_runtime.interpreter', 'tflite_runtime.interpreter._interpreter'],
    # ...其他配置
)

3. 在.spec文件中排除tensorflow

有时候PyInstaller会误判依赖,尝试自动引入tensorflow,我们可以手动排除它,避免不必要的依赖查找:
在.spec文件的Analysis部分添加excludes=['tensorflow']:

a = Analysis(
    ['your_script.py'],
    # ...其他配置
    excludes=['tensorflow'],
    # ...其他配置
)

4. 使用纯净的虚拟环境打包

确保打包环境里只安装了必要的依赖:tflite_runtime、PyInstaller和你的脚本所需的其他包,不要安装完整的tensorflow。这样PyInstaller就不会被环境里的tensorflow干扰,只会打包tflite_runtime。

5. 手动添加tflite_runtime的文件到打包目录

如果上面的方法都无效,可以尝试强制把tflite_runtime的整个目录复制到打包后的程序中:

  • Windows系统:
pyinstaller --add-data "C:\path\to\your\env\Lib\site-packages\tflite_runtime;tflite_runtime" your_script.py
  • Linux/macOS系统:
pyinstaller --add-data "/path/to/your/env/lib/pythonX.X/site-packages/tflite_runtime:tflite_runtime" your_script.py

这些方法应该能解决你遇到的问题,我当时用扩展hiddenimports加上排除tensorflow的方法就搞定了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 19:03:10