不同Python代码打包为exe执行Windows关机命令表现不一致问题求助
异常原因及解决方案
你遇到的匹配到指令后仅弹出cmd窗口不执行关机的问题,可通过以下修改直接解决:
- 修正代码逻辑缺陷:原代码存在
os.listdir默认按文件名排序无法取到最新文件、未过滤文件夹直接打开会触发IO错误、相对路径在exe运行时工作目录偏移等问题,同时指定shutdown命令绝对路径避免环境变量异常找不到命令,修正后参考代码如下:
import os import time as t import re import subprocess # 固定shutdown命令绝对路径,避免环境变量异常 SHUTDOWN_CMD = r"C:\Windows\System32\shutdown.exe /s /t 1" # 用脚本所在目录定位attachments,避免exe运行时工作目录偏移 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ATTACH_PATH = os.path.join(BASE_DIR, "attachments") while True: # 过滤出所有文件,排除子文件夹 file_list = [f for f in os.listdir(ATTACH_PATH) if os.path.isfile(os.path.join(ATTACH_PATH, f))] if not file_list: t.sleep(5) continue # 按修改时间倒序取最新文件 latest_file = sorted(file_list, key=lambda x: os.path.getmtime(os.path.join(ATTACH_PATH, x)), reverse=True)[0] current_file = os.path.join(ATTACH_PATH, latest_file) try: # 指定编码读取,避免特殊编码文件报错 with open(current_file, "r", encoding="utf-8", errors="ignore") as f: content = f.read() if "sd" in content: os.remove(current_file) # 使用subprocess调用避免弹出cmd窗口 subprocess.run(SHUTDOWN_CMD, shell=True, creationflags=subprocess.CREATE_NO_WINDOW) break except Exception as e: # 写入错误日志方便排查 with open(os.path.join(BASE_DIR, "run.log"), "a", encoding="utf-8") as log_f: log_f.write(f"处理文件{latest_file}出错:{str(e)}\n") t.sleep(5)
- 打包时添加无窗口参数,如果你使用PyInstaller打包,执行以下命令即可:
pyinstaller -F -w 脚本文件名.py
参数-w会禁用控制台窗口,运行exe时不会弹出黑框。
内容的提问来源于stack exchange,提问作者Taha
相关产品推荐
相关产品推荐

