pythonpython-keyboard

Is there any way to detect a keypress that is executed programmatically?


I want to detect if a keypress was executed programmatically (not by user's physical press). Is there any way to do this?

import mouse
import keyboard
import time


keyboard.press("a")

if keyboard.is_pressed('a'):
    print ("pressed")

I assume 'is_pressed' in the code above only detects actual input from user hence it wouldn't show print ("pressed"). All I could come up with to solve this is the code below which works just fine for my intention but I want to know if there's a better optimized way.

import mouse
import keyboard
import time
    
    
keyboard.press("a")
keyboard_a = True

keyboard.press("b")
keyboard_b = True
    
if keyboard_a:
    print ("a pressed")

if keyboard_b:
    print ("b pressed")    

Solution

  • It is not possible to distinguish between key press events that are triggered programmatically and those that are triggered by user input. The same is true for readchar, msvcrt, or keyboard libraries.

    So, the library provides a way to detect and respond to key press events, regardless of their origin. Hence, your approach with a flag is good.

    I don't know your precise aim, but maybe you would prefer to use send and a register event like this

    import keyboard
    import threading
    
    is_programmatic = False
    
    # Define a function to be called when a specific key is pressed
    def on_key_press(keyEvent):
        global is_programmatic
    
        if keyEvent.name == 'a':
            if is_programmatic:
                print("Key press event triggered programmatically")
            else:
                print("Key press event triggered by user input")
        
            is_programmatic = False
    
    # Register listener
    keyboard.on_press(on_key_press)
    
    # Start keyboard listener
    keyboard.wait()
    
    # or start a thread with the listener (you may want to sleep some seconds to wait the thread)
    thread = threading.Thread(target=keyboard.wait)
    thread.start()
    

    and to issue the event

    is_programmatic = True
    keyboard.send("a")