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

Python脚本使用auto-py-to-exe转exe后闪退无通知问题求助

问题核心原因
  • 代码中硬编码了本地绝对路径的图标文件,打包后exe运行时找不到对应路径的ico文件,直接触发异常退出
  • plyer库的Windows平台通知模块属于隐式依赖,auto-py-to-exe默认不会自动打包,运行时缺依赖报错
  • lxml、bs4的部分底层依赖也可能存在打包遗漏的情况
  • 代码没有全局异常捕获,报错后直接退出,看不到具体错误信息,就表现为终端一闪而过
修复步骤

1. 替换硬编码的绝对路径,添加全局异常捕获

将你的代码替换为下方修改后的版本,把dictionary.ico放到和脚本同目录下:

import urllib.request
from bs4 import BeautifulSoup
import time
from plyer import notification
import os
import traceback

if __name__ == '__main__':
    try:
        # 动态获取当前运行目录,兼容脚本和exe运行场景
        current_path = os.path.dirname(os.path.abspath(__file__))
        icon_path = os.path.join(current_path, "dictionary.ico")
        
        url = "https://www.dictionary.com/e/word-of-the-day/"
        html_file = urllib.request.urlopen(url)
        soup = BeautifulSoup(html_file, 'lxml')

        soup1 = soup.find(class_="otd-item-headword__word")

        try:
            soup1 = soup1.get_text()
        except AttributeError:
            # 错误输出到日志文件
            with open(os.path.join(current_path, "vocab_log.txt"), "a", encoding="utf-8") as f:
                f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} 今日无新词\n")
            exit()

        txt10 = soup1.rstrip()
        soup2 = soup.find(class_="otd-item-headword__pos")
        soup2 = soup2.get_text()
        txt11 = soup2.rstrip()

        notification.notify(
            title="*** 每日新词 ***" + "\n" + ' '.join(txt10.split()) + "\n",
            message="释义:" + ' '.join(txt11.split()),
            app_icon=icon_path,
            ticker=r"背单词应用",
            app_name=r"Python项目:365每日新词",
            timeout=60
        )
        time.sleep(60 * 60)
    except Exception as e:
        # 所有异常都写入日志,方便排查问题
        current_path = os.path.dirname(os.path.abspath(__file__))
        with open(os.path.join(current_path, "vocab_log.txt"), "a", encoding="utf-8") as f:
            f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} 运行报错:{str(e)}\n")
            f.write(traceback.format_exc() + "\n")

如果暂时不需要自定义图标,可以直接注释掉app_icon参数先测试,排除图标问题影响

2. 调整auto-py-to-exe打包配置

  • 「脚本位置」选择你修改后的py文件
  • 「附加文件」点击添加文件,选择你的dictionary.ico文件,打包时会一起输出
  • 「高级」-「隐藏导入」栏输入以下内容,多个用空格分隔:
    plyer.platforms.win.notification lxml bs4
  • 排查阶段可以先选择「基于控制台的程序」,运行时会保留黑框显示报错,确认正常运行后再改成「基于窗口的程序」隐藏后台运行
  • 点击打包即可,打包完成后运行生成的exe,要是还有问题直接看同目录生成的vocab_log.txt日志就能定位具体原因

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:27:04