Windows CMD中Python脚本防外部暂停及重启事件检测问询
解决Windows CMD中Python脚本被鼠标点击暂停的问题
你遇到的是Windows CMD默认开启的快速编辑模式导致的现象:当你在CMD窗口内点击或按住鼠标时,系统会暂停当前运行的进程(包括Python脚本的控制台输出和文件写入),直到按下回车或Esc键才会恢复执行。
1. 如何让Python脚本避免此类外部暂停?
有两种可靠的解决方式:
方式一:手动关闭CMD的快速编辑模式
- 打开CMD窗口,右键点击顶部标题栏,选择「属性」(若要让所有新CMD窗口生效,选「默认值」)
- 切换到「编辑选项」标签页
- 取消勾选「快速编辑模式」和「插入模式」,点击确定即可。
方式二:通过Python代码禁用快速编辑模式
如果希望脚本自动生效,不用手动修改CMD设置,可以调用Windows API直接修改控制台模式:
import ctypes import datetime import time # 调用Windows内核API修改控制台输入模式 kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) std_input_handle = kernel32.GetStdHandle(-10) # 获取标准输入句柄 console_mode = ctypes.c_uint32() # 获取当前控制台模式 kernel32.GetConsoleMode(std_input_handle, ctypes.byref(console_mode)) # 关闭快速编辑模式(0x0040)和插入模式(0x0020) kernel32.SetConsoleMode(std_input_handle, console_mode.value & ~(0x0040 | 0x0020)) # 你的原有脚本逻辑 while datetime.datetime.now().hour < 16: current_time = datetime.datetime.now() print(current_time) with open("dump.txt", "at") as f: f.write(f"t: {current_time}\n") time.sleep(5)
这段代码会在脚本启动时自动禁用快速编辑模式,彻底避免鼠标点击导致的暂停。
2. 能否在Python中检测此类事件(至少检测重启)?
- 无法直接检测暂停事件:因为进程被系统挂起时,Python代码完全停止执行,没有机会运行检测逻辑。
- 可以检测恢复运行的时刻:通过记录循环的时间间隔来判断。如果实际间隔远大于预期的睡眠时间,说明程序被暂停过。示例代码:
import datetime import time interval = 5 # 预期的循环间隔(秒) last_exec_time = datetime.datetime.now() while datetime.datetime.now().hour < 16: current_exec_time = datetime.datetime.now() # 计算实际间隔,超过预期的2倍则判定为被暂停过 time_diff = (current_exec_time - last_exec_time).total_seconds() if time_diff > interval * 2: print(f"程序在 {last_exec_time} 到 {current_exec_time} 期间被暂停过") print(current_exec_time) with open("dump.txt", "at") as f: f.write(f"t: {current_exec_time}\n") last_exec_time = current_exec_time time.sleep(interval)
原理是:程序被暂停时,time.sleep(5)不会正常走完,进程挂起期间时间会持续流逝,恢复后计算的时间差会远大于设定的5秒,以此识别暂停恢复事件。
内容的提问来源于stack exchange,提问作者Borut Flis
相关产品推荐
相关产品推荐

