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

使用py2exe将Python文件打包为exe时触发RuntimeError报错如何解决

报错根因

这个报错是py2exe打包时尝试编译IDE调试工具(debugpy/pydevd)的冗余模块导致的:你从VSCode/PyCharm等IDE直接启动运行代码时,环境会自动注入调试相关的依赖,打包时这些不需要的模块被纳入编译流程就会触发错误。


解决步骤

1. 用原生终端执行打包命令

完全关闭当前IDE,打开系统自带的cmd/powershell终端,切换到代码目录C:/Users/Murat/Desktop/Combobox/后直接执行打包命令,不要用IDE的运行/调试按钮触发打包:
python setup.py py2exe

2. 修改setup.py配置

  • 移除setup.py中不必要的业务代码依赖导入,避免额外引入冗余模块
  • 新增excludes配置,过滤所有调试相关模块
  • 增加源码过滤逻辑,避免把py文件也打包到静态资源里

修改后的完整setup.py代码如下:

from distutils.core import setup
import py2exe
import os

includes = ["tkinter", "sys", "lxml._elementpath"]
packages = ["tkinter", "docx", "pandas"]
# 排除调试相关冗余模块
excludes = ["debugpy", "_pydev_imps", "_pydevd", "pydevd"]

if __name__ == '__main__':
    Mydata_files = []
    for files in os.listdir("C:/Users/Murat/Desktop/Combobox/"):
        # 过滤源码文件和打包临时目录,避免冗余打包
        if files.endswith('.py') or files.endswith('.pyc') or files in ('build', 'dist'):
            continue
        f1 = "C:/Users/Murat/Desktop/Combobox/" + files
        if os.path.isfile(f1):
            # 所有静态资源会被放到打包后的images目录下
            f2 = 'images', [f1]
            Mydata_files.append(f2)

    setup(
        console = ['Combobox.py'],
        data_files = Mydata_files,
        options={
            "py2exe":{
                "compressed": 0,
                "includes": includes,
                "packages": packages,
                "excludes": excludes,
                "unbuffered": True,
                "optimize": 2,
                "bundle_files": 1,
                "dist_dir": ".",
                "xref": False,
                "skip_archive": False,
                "ascii": False
            }
        }
    )

3. 验证打包结果

运行生成的exe前需要确认:你的业务代码中读取docx、xlsx、图片的路径要统一调整为从./images/目录下读取,否则会出现文件找不到的错误。如果后续出现其他依赖缺失的报错,把对应模块名加到includes或packages配置中即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:06:05