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

cx_Freeze打包TensorFlow程序时出现模块导入缺失问题

解决cx_Freeze打包TensorFlow程序时的ModuleNotFoundError问题

看起来你遇到了cx_Freeze打包TensorFlow项目时常见的模块识别问题——protobuf生成的tfprof_log_pb2模块没被正确打包进去。这种情况通常是因为cx_Freeze没法自动追踪到TensorFlow内部一些动态生成或结构特殊的模块,下面给你几个可行的解决方案:

方案1:让cx_Freeze完整打包TensorFlow模块

手动添加单个文件很容易遗漏依赖,不如直接让cx_Freeze处理整个TensorFlow包:

  • 修改setup.py里的packages列表,把tensorflow加进去,同时调整includes确保关键模块被覆盖:
from cx_Freeze import setup, Executable
import os
import sys
import tensorflow  # 导入tensorflow以便获取其路径

os.environ['TCL_LIBRARY'] = "C:\\Program Files\\Python36\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\Program Files\\Python36\\tcl\\tk8.6"
base = None
if sys.platform == "win32":
    base = "Win32GUI"

includes = [
    "tkinter", "_tkinter", 
    "numpy.core._methods", "numpy.lib.format",
    "tensorflow.core.profiler.tfprof_log_pb2",  # 明确指定要包含的缺失模块
    "tensorflow.python.profiler.profiler"
]
# 用相对路径替代硬编码,避免环境差异
include_files = [
    "C:\\Program Files\\Python36\\DLLs\\tcl86t.dll", 
    "C:\\Program Files\\Python36\\DLLs\\tk86t.dll", 
    "C:\\Program Files\\Python36\\DLLs\\_tkinter.pyd",
    # 添加TensorFlow profiler的整个目录,确保所有依赖文件都被打包
    (os.path.join(os.path.dirname(tensorflow.__file__), "core", "profiler"), "tensorflow/core/profiler"),
    (os.path.join(os.path.dirname(tensorflow.__file__), "python", "profiler"), "tensorflow/python/profiler")
]
packages = ["tensorflow"]  # 让cx_Freeze自动处理TensorFlow的所有子模块

setup(
    name = "Ap'Pear", 
    version = "0.1", 
    description = "Test executable", 
    options = {
        "build_exe": { 
            "includes": includes, 
            "include_files": include_files, 
            "packages": packages
        }
    }, 
    executables = [
        Executable(
            script = "main.py", 
            targetName = "Ap'Pear.exe", 
            base = base, 
            icon = "images/icon.ico"
        )
    ], 
)

方案2:在主脚本中提前触发模块导入

cx_Freeze会根据主脚本中实际导入的模块来打包,你可以在main.py的最开头主动导入缺失的模块,让cx_Freeze检测到它:

# main.py开头添加
from tensorflow.core.profiler.tfprof_log_pb2 import OpLogProto
from tensorflow.python.profiler import profiler

# 然后再导入你的其他依赖和代码
import tensorflow as tf
# ... 你的其他代码

这样打包时cx_Freeze就会把这些模块包含进去。

方案3:检查版本兼容性

Python3.6对应的TensorFlow应该是1.x系列(比如1.15.x),而cx_Freeze最好使用5.x版本(比如5.1.1),高版本的cx_Freeze可能对旧Python/TensorFlow支持不好。你可以卸载当前cx_Freeze,安装指定版本:

pip uninstall cx_Freeze
pip install cx_Freeze==5.1.1

额外注意事项

  • 不要手动复制单个.py或.h文件,而是打包整个目录,这样能保证所有关联的依赖文件(比如.pyc、protobuf相关的辅助文件)都被包含。
  • 打包后可以打开生成的build目录,检查tensorflow/core/profiler下是否有tfprof_log_pb2.py文件,确认它被正确复制到了对应路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:29:25