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
Answer from user8167727 on Stack OverflowPython 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.
Here is the pynput official "Monitoring the keyboard" source code example:
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()
I'm currently trying to make the use of the keyboard function keyboard.is_pressed() a bit more generic. Most use some line of code for each indivisual key, I would like to use the dictonary keys as possible input.
So I have a dict with different keyboard commands as keys and want it to react as soon as one of them is pressed. In my first try I didn't provide a particular key:
import keyboard
import time
test = {'1': 'Test1', '2': 'Foo', '3': 'Bar'}
while True:
if keyboard.is_pressed('+'):
time.sleep(1)
while keyboard.is_pressed('-') != True:
input = keyboard.is_pressed() #<- how can I use all Dict Keys here?Which of course lead to the TypeError:
> is_pressed() missing 1 required positional argument: 'hotkey'.
I also tried `keyboard.is_pressed(test.keys())` which leads to
> TypeError: expected string or bytes-like object
Is there a way that I can use `keyboard.is_pressed()` with my dict keys or a list of possible keyboard keys?
How does keyboard.is_pressed() work in Python? - Stack Overflow
How to detect a keypress when the program is running?
pi 5 - module 'keyboard' has no attribute 'is_pressed' - I have trouble using pynput or keyboard libraries - Raspberry Pi 5 - Raspberry Pi Stack Exchange
Need help stopping an infinite loop with a key press
Videos
ยป pip install keyboard
I know that it was a year ago, but I have found this question today.
Sooo, according to the Keyboard API:
keyboard.press(hotkey) emulates pressing a hotkey on keyboard.
keyboard.release(hotkey) emulates releasing a hotkey on keyboard.
A hotkey is an key number, key name, or combination of two or more keys.
keyboard.press_and_release(hotkey) or keyboard.send(hotkey) emulates pressing and releasing a key or hotkey.
Pressing and releasing behaviour depends on values of do_press and do_release when using keyboard.send().
For example:
keyboard.send('space', do_press=True, do_release=True)
will emulate pressing and releasing space key, but:
keyboard.send('space', do_press=False, do_release=True)
will emulate only releasing space key.
keyboard.is_pressed(key) returns True if a specified key has been pressed, and False otherwise
Hope I've helped!
keyboard.is_pressed() is basically checking if a certain key code is pressed. If you put keyboard.is_pressed('x'), it will basically check if the letter x is being pressed, using its keycode, 88.
On the other hand, I can see that the majority of the script works, checking if 'u' is pressed, and then 'elseif's appear fine, but I don't know fully why this part, keyboard.release('w'), is at the very bottom. I suggest either removing this line lines:
else: # (this line is fine)
print(4) # (this line is fine)
keyboard.release('w')
and adjusting the lines a wee bit for this completed code!
while True:
if keyboard.is_pressed('u'):
keyboard.press('w')
keyboard.release('w')
print(0)
elif keyboard.is_pressed('j'):
#keyboard.press_and_release('s')
print(1)
elif keyboard.is_pressed('k'):
#keyboard.press_and_release('d')
print(2)
elif keyboard.is_pressed('h'):
#keyboard.press_and_release('a')
print(3)
else:
print("No Key pressed.") #alternatively, you can keep it as print(4).
Hope this helped, despite being over 4 years late.
I have a program which takes user input and outputs an answer. Now, I'd like to make it so that when the user presses a certain key, it exits the program. But how can you make it so that the program tries to detect that exit keypress at all times? Even when its looking for a user input?
I am only able to do one step at a time, like user input/output, then exit, or I can put exit first but that will just exit before anything happens
Thanks in advance!
Hi guys, so my goal for this program is to have the program continuously print "test". I want the program to stop printing "test" immediately once the user types in a specific key (ex. Enter, Down Arrow, a) and store a string in the variable "key_pressed". The way this program currently works, it will only stop the loop if the user is pressing the key right when the "if keyboard.is_pressed("a")" line is active. I don't know how to make this work, do you guys have any ideas?
import time
import keyboard
while True:
time.sleep(0.5) # pause for half a second
print("test")
if keyboard.is_pressed("a"): # check if the A key is pressed (I want to be able to detect other keys such as the Down arrow key)
key_pressed = str("A was pressed")
break # exit the loop
print(key_pressed)