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()
How do you detect key presses in python? - Computer Science - Snap! Forum
How to detect keypress in python using keyboard module? - Stack Overflow
Can I detect a key press from an external keyboard?
How do I use the Python keyboard module to detect a key press? - Stack Overflow
Videos
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!
First of all, you forgot to close the strings on lines 4 and 6.
But your main issue is that you call keyboard.read_key() once for each arm of your if statement. This makes your code wait for a keypress, check if it's 'enter', then wait for another keypress, check if it's 'q', and so on.
What you should do is save the key to a variable, then check the variable. It should look something like this:
import keyboard
while True:
key = keyboard.read_key()
if key == 'enter':
print('Enter is pressed')
if key == 'q':
print('Quitting the program')
break
if key == 's':
print('Skiping the things')
As per Keyboard documentation:
Other applications, such as some games, may register hooks that swallow all key events. In this case keyboard will be unable to report events.
One way to solve your problem with keyboard module is keyboard.wait('key')
# Blocks until you press esc
keyboard.wait('esc')
Something work around is as below:
import keyboard
keyboard.wait('enter')
print('Enter is pressed')
keyboard.wait('q')
print('Quitting the program')
keyboard.wait('s')
print('Skiping the things')
Let's say I use a USB number pad
I want to write code so that if a key on the number pad is pressed, then some action happens
Can I do this in Python?
I searched for the answer before posting. I see lots of links for detecting key presses - but I can't find anything for a specific key on a specific external device
Thanks
» pip install keyboard
There are usually many different ways to code something. Some are better than others. In a problem that is based on keyboard input, like your cash register/adding machine project, I would go with an event-driven approach. Your sample code represents a polling approach. It can work, but it may not be as efficient.
I've never used the keyboard module before, but I did some quick research and came up with the below program, which may give you guidance. Every time a key in the keyboard is pressed, the key_pressed() routine is triggered. Digits are stored, and the Enter key causes an addition and then clearing of the stored digits.
import keyboard
sin = ""
val = 0.0
def key_pressed(e, *a, **kw):
global sin, val
# print(e, a, kw)
k = e.name
if k in "0123456789":
sin += k
elif k == 'enter':
val += float(sin)/100.0
print("Entered: " + sin)
print('Value: ', val)
sin = ""
keyboard.on_press(key_pressed)
I took a look at the documentation located here https://github.com/boppreh/keyboard.
I ran and tested this code on python 3.9
import keyboard
from functools import partial
num = ""
def add(i):
global num
num += str(i)
print(num, end='\r')
for i in range(10): # numbers 0...9
keyboard.add_hotkey(str(i), partial(add, i)) # add hotkeys
keyboard.wait('enter') # block process until "ENTER" is pressed
print("\nNum:{}".format(num))
You could additionally unhook the hotkeys by calling keyboard.unhook_all_hotkeys() after grabbing the number. I imagine you could wait on "+" and "-" if you wanted to implement addition and subtraction of numbers.