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

PyInstaller打包的exe无法启动,CPU占用100%求助

问题排查与解决步骤

1. 移除致命的自动安装逻辑

你的代码开头尝试自动安装tk,但打包成exe后,sys.executable指向的是打包后的exe文件而非Python解释器。执行subprocess.check_call([python,'-m','pip','install', *missing])会触发无限递归启动自身,这就是CPU占用100%、程序无响应的核心原因。

直接删除这段无效且危险的代码:

import sys, subprocess, pkg_resources

required={'tk'}
installed={pkg.key for pkg in pkg_resources.working_set}
missing=required - installed

if missing:
    python=sys.executable
    subprocess.check_call([python,'-m','pip','install', *missing],stdout=subprocess.DEVNULL)

tkinter是Python标准库,PyInstaller打包时会自动包含,无需额外安装。

2. 修复tkinter事件绑定的参数问题

你用root.bind("<Return>", crawler)绑定了回车事件,但crawler函数没有接收事件参数,触发回车时会抛出异常(若控制台被隐藏则无法看到报错)。修改crawler函数:

def crawler(event=None):  # 添加可选的event参数适配绑定事件
    ttk.Label(mainframe, text="...data retrieving finished. Check file ...").grid(column=0, row=6, sticky='W')
    root.update()

3. 使用正确的PyInstaller打包参数

打包时添加--windowed(或-w)参数隐藏命令行窗口,还可通过参数优化打包效果:

# 生成单文件exe(启动稍慢,便于分发)
pyinstaller --windowed --onefile your_script.py

# 生成文件夹形式exe(启动更快,适合本地使用)
pyinstaller --windowed --onedir your_script.py

若要缩小体积,可添加--exclude-module排除不必要的依赖(比如--exclude-module matplotlib,如果你的代码没用到)。

4. 处理selenium驱动路径问题

打包selenium时,需确保ChromeDriver路径正确:

  • 若用单文件打包,需把ChromeDriver和脚本放同目录,打包时通过参数包含驱动:
    pyinstaller --windowed --onefile --add-binary "chromedriver.exe;." your_script.py
    
    同时代码里用临时目录获取驱动路径:
    import sys, os
    def get_driver_path():
        if getattr(sys, 'frozen', False):
            return os.path.join(sys._MEIPASS, 'chromedriver.exe')
        else:
            return 'chromedriver.exe'
    
    service = Service(executable_path=get_driver_path())
    driver = webdriver.Chrome(service=service)
    
  • 若用文件夹打包,直接把ChromeDriver放在生成的exe同目录即可。

5. 提前验证依赖完整性

打包前确保所有第三方依赖(openpyxl、pandas、selenium)都已在本地环境正确安装,避免PyInstaller打包时遗漏依赖导致运行时错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:05:26