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

如何实现按下指定键盘按键即可立即终止运行中的Python代码

根因说明

你的代码按键检测逻辑放在m()函数调用之后,而m()内部的time.sleep()会阻塞主线程,阻塞阶段程序不会执行任何代码,自然无法检测按键状态,必须等休眠结束、走完一轮循环才会触发一次按键检测,所以需要多次按键才能刚好卡在检测时间点触发终止。

可行实现方案

方案1:使用异步热键绑定(最简便,立刻响应)

利用keyboard库的事件回调机制,热键触发逻辑是异步运行的,不受主线程sleep阻塞,按下按键的瞬间就会触发回调执行终止逻辑,修改后代码如下:

import pyautogui as pg
import keyboard
import time
import sys
from PIL import Image

button = "p"

# 终止回调函数
def stop():
    print("stopped")
    sys.exit()

# 绑定热键
keyboard.add_hotkey(button, stop)

def m():
    if pg.locateOnScreen('Screenshot_2.png', confidence = 0.9):
        pc = pg.locateOnScreen('Screenshot_2.png', confidence = 0.9)
        pg.center(pc)
        pg.click(pc)
        print('found!')
        time.sleep(2)
    else:
        time.sleep(3)
        print('not found!')
        
while True:
    m()

这个方案不需要改原有业务逻辑,只需要加3行代码就能实现按下按键立刻终止的效果。

方案2:拆分长休眠为多次短休眠(适合需要做退出前清理的场景)

如果你需要在退出前执行资源释放、状态保存等清理逻辑,不想直接调用sys.exit()强制退出,可以把长休眠拆分为多个100ms级别的短休眠,每次休眠前都检测一次按键状态,检测到按下就终止循环:

import pyautogui as pg
import keyboard
import time
from PIL import Image

button = "p"
stop_flag = False

# 自定义可中断休眠函数
def interruptible_sleep(duration):
    global stop_flag
    # 按100ms粒度拆分休眠
    for _ in range(int(duration * 10)):
        if keyboard.is_pressed(button):
            stop_flag = True
            return
        time.sleep(0.1)
    # 处理非整数秒的剩余休眠时间
    remaining = duration % 0.1
    if remaining > 0 and not stop_flag:
        time.sleep(remaining)

def m():
    global stop_flag
    if pg.locateOnScreen('Screenshot_2.png', confidence = 0.9):
        pc = pg.locateOnScreen('Screenshot_2.png', confidence = 0.9)
        pg.center(pc)
        pg.click(pc)
        print('found!')
        interruptible_sleep(2)
        if stop_flag:
            return
    else:
        interruptible_sleep(3)
        if stop_flag:
            return
        print('not found!')
        
while True:
    m()
    if stop_flag:
        print("stopped")
        break

这个方案的按键响应延迟最高只有100ms,人感知不到,同时可以在退出前插入你需要的清理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:39:04