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

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!

Related

How to detect keypress in python using keyboard module?

I am making a program in python to detect what key is pressed and based on my keyboard it will make a decision.
I want to implement it using keyboard module in python.
I would do something like this,
import keyboard
while True:
if keyboard.read_key() == 'enter':
print('Enter is pressed)
if keyboard.read_key() == 'q':
print('Quitting the program)
break
if keyboard.read_key() == 's':
print('Skiping the things')
But it doesn't work. When I execute this program, I have to press s twice to execute the "s" block.
Also, I have a problem that is after the execution is finished, it writes all the keys in my command prompt is it possible to fix that?
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')
As Far I Know There is only one efficient way to Detect user input weather it keybored or mouse input Which is library called pynput ......
from pynput.keyboard import Key , Listener , Controller
keyboard = Controller()
DoubleShot=False
shot=False
def on_press(key):
global DoubleShot
global shot
if Key.num_lock == key:
print("activate")
DoubleShot=True
if DoubleShot:
if Key.shift == key:
shot = not shot
if shot:
keyboard.press(Key.shift)
keyboard.release(Key.shift)
def on_release(key):
if key == Key.esc:
return False
with Listener(on_press=on_press , on_release=on_release) as listener:
listener.join()
i create this for a game to shoot multiple time on 'shift' clicked
code activate only when ' numlock ' clicked.....
Controller is for clicking any key you want
Note:
In My case infinity looping was a problem that's why shot variable is there to stop looping

Typing Test, how to make input save when spacebar is pressed

My friend and I were building a typing test. We are using the input() function in python to get input from the user. The problem is that we have to press enter to make the input save and we want that button to be spacebar instead. Is there any way to do this or another module we could use to solve this problem?
for i in range(num_words):
print(final_sentence)
print("")
typed_word = input("Type>")
words_to_list(typed_word)
os.system('clear')
You should probably use other modules like keyboard or pynput because input() detects whole strings while those modules detect key presses. Detect key presses, print them, and stop when Key.space (in pynput case) is pressed.
Something like this:
from pynput.keyboard import Listener
from pynput.keyboard import Key
words=''
def on_press(key):
if key==Key.space:
listener.stop()
print (words)
def on_release(key):
global words
typed = str(key).replace("'", "")
words = words + typed
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
This code detects key press using pynput.keyboard's handy listener, and adds it to words until space is pressed. When space is pressed the script stops the listener and prints the typed sentence.

Breaking a loop without ending the program (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:)

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.

{Py3} How do I get a user to press a key and carry on the program without pressing enter after?

from time import sleep
alive = True
while alive == True:
print("You have awoken in a unknown land.")
sleep(2)
print("\nDo you go north, south, east or west?")
print("Press the up arrow to go north.")
print("Press the down arrow to go south.")
print("Press the left arrow to go west.")
print("Press the right arrow to go east.")
input(" ")
How do I get the user to press one of the arrow keys and have the program carry on without the need of pressing the enter key?
Thanks in advance!
~Lorenzo
You may look into a package like pynput for multiplatform support. Pynput implements mouse and keyboard listeners. This will also allow you to do WSAD movement in your RPG-like game.
For keyboard listeners, you can have a onpress/onrelease key. The help files will have some better examples.
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
If you want to use up/down/left/right (arrow keys) for movement, this may be the easiest least painful solution too.
You Could Make Options Like:
option = input('1/2/3/4:')
or:
Python has a keyboard module with many features. You Can Use It In Both Shell and Console.
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('up'): #if key 'up' is pressed.You can use right,left,up,down and others
print('You Pressed A Key!')
#your code to move up here.
break #finishing the loop
else:
pass
except:
break #if user pressed other than the given key the loop will break
You can set it to multiple Key Detection:
if keyboard.is_pressed('up') or keyboard.is_pressed('down') or keyboard.is_pressed('left') or keyboard.is_pressed('right'):
#then do this
You Can Also Do Something like:
if keyboard.is_pressed('up') and keyboard.is_pressed('down'):
#then do this
It Also Detect Key For The Whole Windows.
Thanks.

Categories

Resources