Related to detect key press in python?
We can detect any ASCII character key press from the answers there but is there any way to detect keys like 'Ctrl,Alt, function keys(F1, F2..) etc.
Preferably for windows.
Related to detect key press in python?
We can detect any ASCII character key press from the answers there but is there any way to detect keys like 'Ctrl,Alt, function keys(F1, F2..) etc.
Preferably for windows.
For detecting ctrl or alt or any function key like f5 f6 , you have to make your own function.
This code will print witch key you press so you come to know the string for a special. key.
import msvcrt
while True:
if msvcrt.kbhit():
key_stroke = msvcrt.getch()
print(key_stroke) # will print which key is pressed
For Example, this code is for detection F6 keypress
import msvcrt
while True:
if msvcrt.kbhit():
key_stroke = msvcrt.getch()
c1 = "b\'\\x00\'"
c2 = "b\'@\'"
if str(key_stroke) == str(c1):
key_stroke = msvcrt.getch()
if str(key_stroke) == str(c2):
print('yes')
I hope it's work for you.
Simplest cross platform solution is sshkeyboard. It handles parsing the msvcrt output into readable characters.
Install with pip install sshkeyboard,
then write script such as:
from sshkeyboard import listen_keyboard
def press(key):
print(f"'{key}' pressed")
def release(key):
print(f"'{key}' released")
listen_keyboard(
on_press=press,
on_release=release,
)
And it will print:
'a' pressed
'a' released
When A key is pressed. ESC key ends the listening by default.