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 OverflowIm trying to read my keyboard input with the read_key() method. If i type slowly it will detect every key press. However, if i type fast then i will get multiples of the same key and completely miss other keys. Is this because the read_key() function cant keep up?
This program is still in its early stages but here is the code.
Import keyboard
recording = True keys = []
while recording: keys.append(keyboard.read_key()) if keyboard.read_key() == “esc”: recording = False
print(keys)
Edit: formatted with indents for the while loop and if statements. Just does not show indents when posted.
Where to Place the `readkey()` Function in the Python Standard Library?
python - How to detect key presses? - Stack Overflow
python - keyboard.read_key() records 2 events - Stack Overflow
python - How to read keyboard input? - Stack Overflow
» pip install keyboard
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.
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()
It is probably registering both key down and key up. You can use an auxiliary variable to only register it once:
import keyboard
from datetime import datetime
running = True
counter = 0
not_pressed = True
while running:
input = keyboard.read_key(suppress = True)
if input== "esc":
print (counter)
running = False
else:
if not_pressed:
counter += 1
dateTimeObj = datetime.now()
print(counter,dateTimeObj)
not_pressed = False
else:
not_pressed = True
maybe your program is registering events when you are pressing the key and when you releasing the key?
maybe the keyboard.record() will help you
# Record events until 'esc' is pressed.
recorded = keyboard.record(until='esc')
here is the description to keyboard module
Use
input('Enter your input:')
if you use Python 3.
And if you want to have a numeric value, just convert it:
try:
mode = int(input('Input:'))
except ValueError:
print("Not a number")
If you use Python 2, you need to use raw_input instead of input.
It seems that you are mixing different Pythons here (Python 2.x vs. Python 3.x)... This is basically correct:
nb = input('Choose a number: ')
The problem is that it is only supported in Python 3. As @sharpner answered, for older versions of Python (2.x), you have to use the function raw_input:
nb = raw_input('Choose a number: ')
If you want to convert that to a number, then you should try:
number = int(nb)
... though you need to take into account that this can raise an exception:
try:
number = int(nb)
except ValueError:
print("Invalid number")
And if you want to take advantage of formatting through f-strings:
print(f"Number: {number}\n")
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')