Visit Keyboard Checker and tap the key you want to test. If a key on the on-screen keyboard turns green, that means the keypress is being recognized however, the keyboard you see is NOT going to be an accurate representation of the keyboard you're using.
Note: The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers. To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.
In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.
Python has a keyboard module with many features. Install it, perhaps with this command:
pip3 install keyboard
Then use it in code like:
import keyboard # using module keyboard
while True: # making a loop
try: # used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
except:
break # if user pressed a key other than the given key the loop will break
For those who are on windows and were struggling to find an working answer here's mine: pynput
from pynput.keyboard import Key, Listener
def on_press(key):
print('{0} pressed'.format(
key))
def on_release(key):
print('{0} release'.format(
key))
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
The function above will print whichever key you are pressing plus start an action as you release the 'esc' key. The keyboard documentation is here for a more variated usage.
Markus von Broady highlighted a potential issue that is: This answer doesn't require you being in the current window to this script be activated, a solution to windows would be:
from win32gui import GetWindowText, GetForegroundWindow
current_window = (GetWindowText(GetForegroundWindow()))
desired_window_name = "Stopwatch" #Whatever the name of your window should be
#Infinite loops are dangerous.
while True: #Don't rely on this line of code too much and make sure to adapt this to your project.
if current_window == desired_window_name:
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
More things can be done with keyboard
module.
You can install this module using pip install keyboard
Here are some of the methods:
Using the function read_key()
:
import keyboard
while True:
if keyboard.read_key() == "p":
print("You pressed p")
break
This is gonna break the loop as the key p is pressed.
Using function wait
:
import keyboard
keyboard.wait("p")
print("You pressed p")
It will wait for you to press p and continue the code as it is pressed.
Using the function on_press_key
:
import keyboard
keyboard.on_press_key("p", lambda _:print("You pressed p"))
It needs a callback function. I used _
because the keyboard function returns the keyboard event to that function.
Once executed, it will run the function when the key is pressed. You can stop all hooks by running this line:
keyboard.unhook_all()
This method is sort of already answered by user8167727 but I disagree with the code they made. It will be using the function is_pressed
but in an other way:
import keyboard
while True:
if keyboard.is_pressed("p"):
print("You pressed p")
break
It will break the loop as p is pressed.
You can use keyboard.record
as well. It records all keys pressed and released until you press the escape
key or the one you've defined in until
arg and returns a list of keyboard.KeyboardEvent
elements.
import keyboard
keyboard.record(until="p")
print("You pressed p")
Notes:
keyboard
will read keypresses from the whole OS.keyboard
requires root on linuxAs OP mention about raw_input - that means he want cli solution. Linux: curses is what you want (windows PDCurses). Curses, is an graphical API for cli software, you can achieve more than just detect key events.
This code will detect keys until new line is pressed.
import curses
import os
def main(win):
win.nodelay(True)
key=""
win.clear()
win.addstr("Detected key:")
while 1:
try:
key = win.getkey()
win.clear()
win.addstr("Detected key:")
win.addstr(str(key))
if key == os.linesep:
break
except Exception as e:
# No input
pass
curses.wrapper(main)
For Windows you could use msvcrt
like this:
import msvcrt
while True:
if msvcrt.kbhit():
key = msvcrt.getch()
print(key) # just to show the result
Use this code for find the which key pressed
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With