How to see what key was just pressed in pynput - python

from pynput import keyboard
from pynput.keyboard import Key, Listener
def on_press(key):
print(f'{key} pressed')
def on_release(key):
print(f'{key} release')
if key == "a":
play_audio("A0.ogg")
if key == Key.esc:
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
what I tried was
if key == "a":
play_audio("A0.ogg")
But it doesn't seem to work.
I am also using a listener.

Two ways to do that:
def on_release(key):
print(f'{key} release')
if key.char == 'a': # when press some specific keys, this will raise an Exception.
play_audio("A0.ogg")
if key == Key.esc:
return False
Or use this directly:
def on_release(key):
print(f'{key} release')
if str(key) == 'a':
play_audio("A0.ogg")
if key == Key.esc:
return False

Related

Simple keyboard program with issues

This program sometimes counts one key press as 2 presses or as 0,5 press.
Program:
import keyboard
while True:
if keyboard.read_key() == 'h':
print("1")
elif keyboard.read_key() == 'j':
print("2")
elif keyboard.read_key() == 'k':
print("3")
I want this program to count 1 key press as one action. I have no clue how to solve this issue.
The keys (events register) are double because you press the "h" key and release the "h" key. The answer is here:
keyboard.read_key() records 2 events
try this:
import keyboard
while True:
event = keyboard.read_event()
if event.event_type == keyboard.KEY_DOWN and event.name == 'h':
print('1')
elif event.event_type == keyboard.KEY_DOWN and event.name == 'j':
print('2')
elif event.event_type == keyboard.KEY_DOWN and event.name == 'k':
print('3')

Python, check if arrow key pressed

How to check if user presses an arrow key in python? I want something like this:
if right_key.pressed():
do_some_shit()
elif left_key.pressed():
do_other_stuff()
In your terminal (or anacoonda prompt) run this command to install pynput library:
pip install pynput
And, in your editor
from pynput import keyboard
from pynput.keyboard import Key
def on_key_release(key):
if key == Key.right:
print("Right key clicked")
elif key == Key.left:
print("Left key clicked")
elif key == Key.up:
print("Up key clicked")
elif key == Key.down:
print("Down key clicked")
elif key == Key.esc:
exit()
with keyboard.Listener(on_release=on_key_release) as listener:
listener.join()
More info
You can use this code:
import keyboard
import time
while True:
try:
if keyboard.is_pressed('left'):
print('You Pressed left!')
time.sleep(0.1)
if keyboard.is_pressed('right'):
print('You Pressed right!')
time.sleep(0.1)
if keyboard.is_pressed('down'):
print('You Pressed down!')
time.sleep(0.1)
if keyboard.is_pressed('up'):
print('You Pressed up!')
time.sleep(0.1)
except:
break
By using listeners you will not have to play an infinite loop. Which I think is more elegant. This code will help you:
from pynput import keyboard
def on_press(key):
if key == keyboard.Key.up:
print('PRESSED')
if key == keyboard.Key.esc:
listener.stop()
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
Note that with 'keyboard.Key' you can detect the key that you want. You can even reproduce the case of holding two keys at the same time and detecting a combination!
This is the code I made, but it's only for a Pygame project with a window
If you need the arrows in pygame I recommend this code:
from pygame.locals import *
import pygame
import sys
window_height = 100
window_width = 100
window = pygame.display.set_mode((window_width, window_height))
# This is the code to check if a player is pushing the arrows
while True:
for evenement in pygame.event.get():
if evenement.type == QUIT or (evenement.type == KEYDOWN and
evenement.key == K_ESCAPE):
print('QUIT')
pygame.quit()
sys.exit()
if evenement.type == KEYDOWN and evenement.key == K_RIGHT:
print("Clicked on the right arrow")
if evenement.type == KEYDOWN and evenement.key == K_LEFT:
print("Clicked on the left arrow")
if evenement.type == KEYDOWN and evenement.key == K_UP:
print("Clicked on the up arrow")
if evenement.type == KEYDOWN and evenement.key == K_DOWN:
print("Clicked on the down arrow")

Keyboard Press Detection with pynput

from pynput import keyboard
def on_press(key):
print('Key %s pressed' % key)
def on_release(key):
print('Key %s released' %key)
with keyboard.Listener( on_press=on_press, on_release=on_release) as listener:
listener.join()
if i keep pressing the F1 button and release,
it says
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 pressed
Key Key.f1 released
if i keep pressing the F1 button and release,i want it to work like below
Key Key.f1 pressed
Key Key.f1 released
Please help me :)
pressed = False
def on_press(key):
global pressed
if not pressed and key == keyboard.Key.f1: # only if key is not held
print('Key %s pressed' % key)
pressed = True # key is held
def on_release(key):
global pressed
if key == keyboard.Key.f1:
print('Key %s released' %key)
pressed = False # key is released
Code is pretty self explanatory, you just provide a boolean pressed that whenever you press the F1 key it is True and whenever you release it, it is False. If press is False you just ignore the on_press "signal".
if you want to achieve this with every key you'll have to store the state of every key in a dictionary (or as similar object).
pressed = {}
def on_press(key):
if key not in pressed: # Key was never pressed before
pressed[key] = False
if not pressed[key]: # Same logic
pressed[key] = True
print('Key %s pressed' % key)
def on_release(key): # Same logic
pressed[key] = False
print('Key %s released' %key)

Python: How to change a keyboard layout in the keylogger?

I am doing keylogger that prints the key I pressed. And I have a problem. When I change my keyboard layout the layout does not change. Please help me.
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()

pynput events executing twice

def pressLetter(charIn):
val = getKeyValue(charIn)
PressKey(val)
return
def KeyboardEvents():
from pynput import keyboard
with keyboard.Events() as events:
for event in events:
if event.key == keyboard.Key.space:
pressLetter('w')
Pressing space types ww. How would I rewrite this so that it only presses w once?
Well, I figured it out. It appears that keyboard.Events() registers button press events on both key pressed and key released. Meaning that...
if event.key == keyboard.Key.space:
pressLetter('w')
Presses w twice because it executes both on key pressed, and then key released.
The solution I found was to use keyboard.Listener() instead
def pressLetter(charIn):
val = getKeyValue(charIn)
PressKey(val)
return
def on_press(key):
if key == keyboard.Key.space:
pressLetter('w')
def on_release(key):
if key == keyboard.Key.esc:
return False
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
listener = keyboard.Listener(on_press=on_press, on_release=on_release)
listener.start()
This worked for me:
def KeyboardEvents():
from pynput import keyboard
with keyboard.Events() as events:
for event in events:
if isinstance(event, keyboard.Events.Press):
if event.key == keyboard.Key.space:
pressLetter('w')

Categories