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")
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, orkeyboardlibraries.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
sendand a register event like thisand to issue the event