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

Pyautogui中含keyboard判断的while True循环仅执行一次的问题求助

问题排查与解决

问题现象

单独执行打印鼠标位置的循环可正常重复运行,但在循环内加入if keyboard.read_key() == "p"的判断逻辑后,循环仅执行一次就停在等待键盘输入的状态,无法继续重复执行循环体内容。

原完整代码:

import pyautogui as pag
import time
import keyboard

print("press 'p' to stop checking your mouse position")

while True:
    time.sleep(0.5)
    print(pag.position())
    
    if keyboard.read_key() == "p":
        print("Checked your position?\n")
        break

x, y = input("input position(x y): ").split()
x = int(x)
y = int(y)
pag.moveTo(x, y, 2) 

while True:
    time.sleep(0.1) 
    pag.click(button='left')

    if keyboard.read_key() == "p":
        print("End\n")
        break

print("Thank you for using ^.^")
time.sleep(0.3)

原因分析

keyboard.read_key()是阻塞式函数,调用后会直接暂停程序运行,直到检测到有按键被按下才会继续执行后续代码。因此第一次循环执行到该判断时,程序就会卡在等待按键输入的状态,无法回到循环开头重复执行打印操作,表现为循环仅运行一次。

解决方案

改用非阻塞的keyboard.is_pressed('p')函数,它只会即时检查指定按键是否处于按下状态,不会暂停程序运行,能保证循环正常重复执行。

修改后的代码:

import pyautogui as pag
import time
import keyboard

print("press 'p' to stop checking your mouse position")

while True:
    time.sleep(0.5)
    print(pag.position())
    
    if keyboard.is_pressed("p"):
        print("Checked your position?\n")
        # 加小延迟避免按键按住时重复触发
        time.sleep(0.2)
        break

x, y = input("input position(x y): ").split()
x = int(x)
y = int(y)
pag.moveTo(x, y, 2) 

print("press 'p' to stop clicking")
while True:
    time.sleep(0.1) 
    pag.click(button='left')

    if keyboard.is_pressed("p"):
        print("End\n")
        time.sleep(0.2)
        break

print("Thank you for using ^.^")
time.sleep(0.3)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:37:17