PyInstaller打包含PySimpleGUI的Python脚本为.exe后无响应,求助排查
打包鼠标自动移动脚本为EXE的问题排查与解决
核心问题原因
- Windows环境下,使用
multiprocessing配合PyInstaller单文件打包时,必须添加multiprocessing.freeze_support(),否则子进程无法正常初始化,导致程序卡住。 - 原代码中主进程启动UI子进程、UI子进程再启动鼠标移动子进程的嵌套结构,在打包后更容易触发进程启动异常。
解决方案与修改步骤
1. 修复多进程打包支持
在主入口处添加multiprocessing.freeze_support(),这是Windows打包多进程脚本的强制要求。
2. 简化进程结构
将UI逻辑放在主进程运行,避免嵌套进程调用,提升打包后的稳定性。
修改后的完整代码
import time import pyautogui import PySimpleGUI as sg import multiprocessing def KeepUI(): sg.theme('Dark') layout = [ [sg.Text('Keep-Me-Up is now running.\nClose it to disable it.')] ] window = sg.Window('Keep-Me-Up', layout) # 启动鼠标移动子进程 p2 = multiprocessing.Process(target=dontsleep) p2.start() while True: event, values = window.read() if event == sg.WIN_CLOSED: if p2.is_alive(): p2.terminate() window.close() break def dontsleep(): while True: for i in range(0, 100): pyautogui.moveTo(1000, i*10) time.sleep(120) if __name__ == '__main__': # 解决Windows打包多进程的关键代码 multiprocessing.freeze_support() # 主进程直接运行UI逻辑,避免嵌套进程 KeepUI()
优化打包命令
使用以下PyInstaller命令打包,隐藏控制台窗口(如需调试可去掉--windowed),并指定生成的EXE名称:
pyinstaller --onefile --windowed --name KeepMeUp filename.py
如果打包后仍出现依赖缺失问题,可手动指定隐藏导入:
pyinstaller --onefile --windowed --hidden-import pyautogui --name KeepMeUp filename.py
内容的提问来源于stack exchange,提问作者Bronzi
相关产品推荐
相关产品推荐

