Breaking a loop without ending the program (python) - python

I have a dictionary with a list of key presses and file names stored in key-value pairs as strings. I want to check if the key pressed is in the dictionary then print the pressed key and the file name associated with it.
My issue is that after I press one key, it keeps looping through the same function and only prints that key. I know I need to stop it from looping, but I don't know how to do that without using "break" or "return" to end the program. The only condition I want the program to end under is if the "esc" key is pressed.
I feel like the answer is ridiculously easy and I'm missing something simple, please help.
Here is my code:
import keyboard
import pygame
# there is more in the dictionary, but it's not much different from what is already pasted here
keys = {"`": "sounds/c2.mp3", "1": "sounds/db2.mp3", "2": "sounds/d2.mp3",}
key = keyboard.read_key()
def sound():
play = keys.get(key, "")
pygame.mixer.init()
pygame.mixer.music.load(play)
pygame.mixer.music.play()
def keypress():
while True:
if key in keys.keys():
if key != "esc":
print(key)
sound()
else:
break
keypress()

I think you need to move key = keyboard.read_key() inside your while loop. (Probably just after while True:)

Related

I want to check if ANY key is pressed, is this possible?

How do I check if ANY key is pressed?
this is how I know to detect one key:
import keyboard # using module keyboard
while True: # making a loop
if keyboard.is_pressed('a'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
How do I check if any key (not just letters) is pressed?
For example, if someone presses the spacebar it works, the same for numbers and function keys, etc.
while True:
# Wait for the next event.
event = keyboard.read_event()
if event.event_type == keyboard.KEY_DOWN:
print(event.name) # to check key name
Press any key and get the key name.
it can be done using the msvcrt module as the following:
import msvcrt
while True:
if msvcrt.kbhit():
key = msvcrt.getch()
break
or the keyboard, although i am not sure of how of a good practice this code is:
import keyboard
while True:
try:
print(keyboard.read_key())
break
except:
pass
if this is bad practice please informe me in the coments so i can mark it as unfavored
thankyou.
Correct solution in Windows is to use msvcrt
Please check thread here:
How to detect key presses?
I think somehow should be possible also with builtin input() command.
Have a nice day!

Turn pynput.keyboard.Key key to an ascii value

For a project I'm working on I need to send keyboard keys pressed in one computer to another. I managed to find pynput and it works pretty well in detecting which key pressed or released. My problem is that if a not alphanumerical key is pressed it returns an object of the type pynput.keyboard.Key which I couldn't find any way to convert into ascii code. This is how a simple code to detect the use of a key looks like:
from pynput import keyboard
def on_press(key):
print(['pressed', key])
def on_release(key):
print(['released', key])
def detect_keyboard():
keyboard.Listener(on_press=on_press, on_release=on_release).start()
if __name__ == '__main__':
detect_keyboard()
while True:
pass
I would really like to know if there is a way to do so, and if not I would be happy for other ideas how to implement my goal.
I understand that it would be tedious, but you could write a dictionary with the key references returning the ascii values. Eg:
from pynput.keyboard import Key
AsciiKeys = {
Key.backspace:8,
Key.esc:27}
Then you would later be able to reference it to get the ascii values.
You will be able to find all of the current keys here: https://pynput.readthedocs.io/en/latest/keyboard.html#pynput.keyboard.Key

How can I mask or hide user input in python without using getpass()?

as the question suggest I am looking for a way to hide or mask user input within python without using the standard getpass library due to using spyder; I am wondering if this would potentially be possible using key pressed and recording each key pressed without it displaying until say enter is pressed? If this is possible would someone be able to help me with a snippet for this purpose
Thanks,
Sam Hedgecock
You should take a look at a kind of key-logging mechanism. You could detect which key the user pressed, store those keys in a buffer to finally output them after ENTER is pressed.
Working cross-platform example:
from getkey import getkey, keys
#Buffer holding all the pressed keys
pressed_keys = []
while True:
#Getting the pressed key
key = getkey()
#Appending it to array
pressed_keys.append(key)
#If ENTER is pressed, exit loop
if key == keys.ENTER:
break
#Outputting all pressed keys after ENTER is pressed
for key in pressed_keys:
print(key, end='')
You need to install getkey though. Use pip3 install getkey.

How to use keyboard event as part of a conditional statement

I'm trying to make a program that outputs a key press event as a response to another keyboard event. How do I get it to use the particular value of the key pressed in a conditional statement? The codes I try seem to be skipping the conditional statement altogether.
Initially tried [if key == '1':], then tired by [if key == 1:]. Also tried various means of assigning [key] to a variable. Also tried [print('2')] instead of using [pyautogui.typewrite('2')]. Tried putting the code both in on_press(key) and in on_release(key).
`
import pyautogui
from pynput.keyboard import Key, Listener
def on_press(key):
print('{0} pressed'.format(key))
def on_release(key):
print('{0} release'.format(key))
k = format(key)
if k == '1': #THIS IS THE PART I CAN'T GET TO WORK
pyautogui.typewrite('2', 0.5)
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()
`
Expected to output '2' whenever I press '1' on the keyboard(in addition to the output of the keypress and keyrelease event). The output for the pressing of '1' doesn't work.
You can use keyboard library, in order to handle/create key events.
while True:
try:
if keyboard.is_pressed('1'):
print('{} is pressed'.format(1))
break
else:
pass
except:
break
the above code runs until 1 is received as a keypress. Upon pressing the key, 1 is pressed will be printed.
You can further use other functions of this library, in order to detect a key down even too.
The key parameter that your on_press/on_release receives is not the character string but rather a Key/KeyChar object, that's why you can't compare it directly with a string.
To access the keyboard input character, use key.char instead:
def on_press(key):
print("pressed '{}'".format(key.char))
Look at the example codes on pynput's documentation on how to capture non letter keys.

how to turn pygame.key.get_pressed() into a key

Doing print pygame.key.get_pressed() prints me lots of 0's, but is there any way that I can print those 0's out as a letter and then sign that letter to a variable?
This is what I mean:
import pygame
pygame.init()
import time
while True:
pressed = pygame.key.get_pressed()
print(pressed) #This prints 0, but I want it to print the button I am pressing
time.sleep(1)
EDIT: I should probaly add that I am working on a scoreboard in pygame and that is why I need to check which button is pressed to be able to enter a name
You can get a list of pressed keys as strings with this piece of code:
pressed = pygame.key.get_pressed() # already familiar with that
buttons = [pygame.key.name(k) for k,v in enumerate(pressed) if v]
print(buttons) # print list to console
pygame.key.name() takes the index of the current list object and returns its name as string. Read more here.
BUT if you are planning to use this list to test for key presses in your code, I highly recommend you to get familiar with pygames way of handling inputs. You can find a tutorial about that here.

Categories

Resources