Python实现Valorant时长统计时while循环无法检测进程退出问题求助
问题根源
- 核心原因是
timer函数内的game变量仅在函数启动时检测了一次进程状态,while循环过程中没有重新检测进程是否存活,所以游戏关闭后循环不会终止 - 冗余的schedule任务:每次
show_name检测到游戏运行就新增一个timer定时任务,最终会同时运行大量重复计时任务,逻辑完全混乱 - 手动计数的方式精度低,也容易出现逻辑错误
修复方案
直接重构逻辑,不需要复杂的schedule嵌套,单循环同时处理进程检测、计时、通知即可,修复后的代码如下:
from win10toast import ToastNotifier import psutil import time def check_game_running(process_name="VALORANT-Win64-Shipping.exe"): return any(p.name() == process_name for p in psutil.process_iter()) if __name__ == "__main__": toaster = ToastNotifier() is_game_running_last = False start_time = 0 notified_minutes = set() # 记录已经推送过通知的时长,避免重复推送 while True: current_running = check_game_running() # 游戏刚启动的情况 if current_running and not is_game_running_last: start_time = time.time() is_game_running_last = True notified_minutes.clear() toaster.show_toast("Valorant计时启动", "已检测到游戏运行,开始计时", duration=10) # 游戏运行中 elif current_running and is_game_running_last: duration_seconds = time.time() - start_time duration_min = int(duration_seconds // 60) # 每30分钟推送一次通知 if duration_min % 30 == 0 and duration_min > 0 and duration_min not in notified_minutes: if duration_min == 30: msg = "你已经玩了30分钟啦" elif duration_min == 60: msg = "你已经玩了1小时啦" elif duration_min == 90: msg = "你已经玩了1小时30分钟啦" else: msg = f"你已经玩了{duration_min//60}小时{duration_min%60}分钟啦" toaster.show_toast("游戏时长提醒", msg, duration=20) notified_minutes.add(duration_min) # 游戏刚关闭的情况 elif not current_running and is_game_running_last: total_seconds = time.time() - start_time total_min = int(total_seconds // 60) total_sec = int(total_seconds % 60) toaster.show_toast("游戏已结束", f"本次总时长:{total_min}分{total_sec}秒", duration=20) is_game_running_last = False time.sleep(1)
优化点说明
- 只保留一个主循环,每秒检测一次进程状态,没有多余的定时任务嵌套
- 用时间戳差值计算时长,精度更高逻辑更简单
- 新增已通知记录,避免同一时长重复推送提醒
- 新增游戏启动、关闭的状态切换检测,逻辑更清晰
内容的提问来源于stack exchange,提问作者George Panagopoulos
相关产品推荐
相关产品推荐

