Python中keyboard.is_pressed()工作原理及按键触发异常排查
Troubleshooting Your Keyboard Simulation Issues & Explaining
keyboard.is_pressed() Hey there, let's break down the problems you're facing and clear up how keyboard.is_pressed() works.
Problem 1: Infinite 'w' Triggers & Broken print() Output
First, let's diagnose why your code is acting up:
- Infinite 'w' triggers: Your
while Trueloop runs as fast as your CPU allows. When you press 'u', every single iteration of the loop detects that 'u' is pressed (even if you hold it for just a split second), and repeatedly runskeyboard.press('w')andkeyboard.release('w'). This makes it look like 'w' is being triggered infinitely. - Broken
print(): Without any delay in the loop, your CPU is maxed out trying to run the loop nonstop. This blocks the output buffer from flushing properly, so yourprint()statements don't show up as expected. When you remove thekeyboardcalls, the loop uses less CPU, letting the buffer refresh normally. - Redundant
keyboard.release('w'): The final line of your code releases 'w' every loop iteration, which can interfere with the intentional release in the 'u' branch.
Fixes for Your Code
Option 1: Use event-based listening (better for single-key triggers)
This approach listens for key presses instead of polling, so you don't get repeated triggers from holding a key:
import keyboard import time # Define functions for each key press def handle_u_press(e): keyboard.press_and_release('w') # Shorthand for press + release print(0) def handle_j_press(e): print(1) def handle_k_press(e): print(2) def handle_h_press(e): print(3) # Bind each key to its handler keyboard.on_press_key('u', handle_u_press) keyboard.on_press_key('j', handle_j_press) keyboard.on_press_key('k', handle_k_press) keyboard.on_press_key('h', handle_h_press) # Keep the program running and print 4 when no keys are pressed try: while True: print(4) time.sleep(0.01) # Add small delay to reduce CPU usage except KeyboardInterrupt: print("Program exited")
Option 2: Modified polling loop (if you prefer keeping the while loop)
Add delays and wait for keys to be released to avoid repeated triggers:
import keyboard import time while True: if keyboard.is_pressed('u'): keyboard.press_and_release('w') print(0) # Wait until 'u' is released to prevent repeated triggers while keyboard.is_pressed('u'): time.sleep(0.01) elif keyboard.is_pressed('j'): print(1) while keyboard.is_pressed('j'): time.sleep(0.01) elif keyboard.is_pressed('k'): print(2) while keyboard.is_pressed('k'): time.sleep(0.01) elif keyboard.is_pressed('h'): print(3) while keyboard.is_pressed('h'): time.sleep(0.01) else: print(4) time.sleep(0.01) # Critical delay to reduce CPU load and fix print issues
How keyboard.is_pressed() Works
Let's keep this straightforward:
keyboard.is_pressed(key)takes a key string (like 'u', 'ctrl', or even 'shift+a') and takes an instant snapshot of your keyboard state to check if that key is currently held down.- It doesn't "listen" for events in the background—it only tells you the state at the exact moment you call it.
- In a tight
while Trueloop, this means it checks the key state hundreds or thousands of times per second. So if you hold a key down, every loop iteration will detect it as pressed, causing repeated actions. - It works for both physical keyboard presses and simulated presses (like the
keyboard.press('w')calls in your code).
内容的提问来源于stack exchange,提问作者Zsolt Ugróczky
相关产品推荐
相关产品推荐

