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

Question:

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")    
Asked By: kerz

||

Answers:

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")
Answered By: Giovanni Minelli

You can create a list and store pressed keys in that list. You can find if a key is pressed by searching that list.

import keyboard

key_pressed = []

keyboard.press("a")
key_pressed.append("a")

keyboard.press("b")
key_pressed.append("b")

keyboard.press("c")
key_pressed.append("c")

#check if a specific key is pressed
if "a" in key_pressed:
    print ("a pressed")

Print all pressed keys:

for key in key_pressed:
    print(key,'pressed')

Print the last pressed key:

print(key_pressed[-1])

You can also create a class to make it easier to use:

import keyboard
class CustomKeyboard():
    def __init__(self):
    self.pressed_keys = []

def press(self, key):
    keyboard.press(key)
    self.pressed_keys.append(key)

def is_pressed_programmatically(self, key):
    if key in self.pressed_keys:
        return True
    return False

Then use it like this:

kb = CustomKeyboard()

kb.press('a')
kb.press('b')

print("did a pressed programmatically?:")
print(kb.is_pressed_programmatically('a'))

print("did z pressed programmatically?:")
print(kb.is_pressed_programmatically('z'))

and here is the output:

is a pressed programmatically?: True

is z pressed programmatically?: False

Answered By: Soroosh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.