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()
Related
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")
I'm trying to make it so that pressing 'r' key will only work after the user pressed 'enter' anytime before. But right now in #1 I can only press 'r' key if I'm holding 'enter' key. I tried in #2 but then the user can just press 'r' without pressing 'enter'.
#1
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_RETURN] or [pygame.K_KP_ENTER]:
print("Do something")
if keys[pygame.K_r]:
print("Do something")
pygame.display.update()
pygame.quit()
#2
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_RETURN] or [pygame.K_KP_ENTER]:
print("Do something")
if keys[pygame.K_r]:
print("Do something")
pygame.display.update()
pygame.quit()
It is very easy to do.
First you need to create a new bool, for example pressed. And then set it to False. Then check if key enter is pressed. If it is then set bool pressed to True. And then check if key r is pressed and if bool pressed is True.
So your code should look like this:
pressed = False
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_RETURN]:
pressed = True
if keys[pygame.K_r] and pressed:
print("Do something")
pygame.display.update()
I hope it helped!
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)
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
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')