如何通过键盘输入立即终止后台运行的Python自动化程序
解决Python自动化程序的紧急终止问题
核心思路
用多线程分离自动化执行逻辑和键盘监听逻辑:在独立线程中监听ESC键,按下时触发终止信号;主程序在关键执行节点检查终止信号,主动停止运行。
修改后的完整代码
import json import threading from pynput import keyboard import automated as auto # 全局终止标志,默认False stop_program = False def on_press(key): global stop_program # 监听ESC键 try: if key == keyboard.Key.esc: stop_program = True print("收到终止信号,程序将尽快停止") # 停止监听 return False except AttributeError: # 忽略普通按键,无需处理 pass def start_key_listener(): # 启动键盘监听线程 with keyboard.Listener(on_press=on_press) as listener: listener.join() if __name__ == "__main__": # 启动监听线程,设为守护线程随主程序退出 listener_thread = threading.Thread(target=start_key_listener, daemon=True) listener_thread.start() # 读取配置数据 with open('mouse.json', 'r') as f: data = json.load(f) account_location = [tuple(lst) for lst in data["account_location"]] tab_location = [tuple(lst) for lst in data["tab_location"]] # 执行自动化步骤,每步后检查终止标志 auto.open_ms() if stop_program: exit() auto.full_screen() if stop_program: exit() auto.scroll_down() if stop_program: exit() auto.open_all_accounts(account_location) if stop_program: exit() for i in range(2): if stop_program: break auto.position_tabs() if stop_program: break count = 0 auto.search_tabs(count, tab_location) if stop_program: break auto.exit_tabs() if stop_program: break if not stop_program: auto.shutdown()
关键说明
daemon=True:将监听线程设为守护线程,主程序退出时会自动终止该线程,避免残留进程- 终止标志检查:在每个自动化步骤后加入判断,确保程序能及时响应终止信号,不会卡在长时间执行的步骤里
- 监听逻辑:捕获ESC键后立即设置终止标志并停止监听,避免重复触发
额外优化建议
- 如果
automated.py中的函数包含循环逻辑,建议在函数内部也加入终止标志的检查,让程序终止更及时 - 可扩展支持其他应急按键(比如F12),只需在
on_press函数中增加对应按键的判断即可
内容的提问来源于stack exchange,提问作者VARUN KHARKWAL
相关产品推荐
相关产品推荐

