Detect key press python

[python] detect key press in python?

I am making a stopwatch type program in python and I would like to know how to detect if a key is pressed (such as p for pause and s for stop), and I would not like it to be something like raw_input that waits for the user’s input before continuing execution. Anyone know how to do this in a while loop?

Also, I would like to make this cross-platform, but if that is not possible, then my main development target is linux

The answer is

Python has a keyboard module with many features. Install it, perhaps with this command:

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

from pynput.keyboard import Key, Listener def on_press(key): print(' pressed'.format( key)) def on_release(key): print(' 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.

Читайте также:  Html float left width 100

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() 

More things can be done with keyboard module. You can install this module using pip install keyboard Here are some of the methods:

Method #1:

Using the function read_key() :

import keyboard while True: if keyboard.read_key() == "p": print("You pressed p") break 

This is gonna break the loop as the key p is pressed.

Method #2:

Using function wait :

import keyboard keyboard.wait("p") print("You pressed p") 

It will wait for you to press p and continue the code as it is pressed.

Method #3:

Using the function on_press_key :

import keyboard keyboard.on_press_key("p", lambda _:print("You pressed p")) 

It needs a callback function. I used _ because the keyboard function returns the keyboard event to that function.

Once executed, it will run the function when the key is pressed. You can stop all hooks by running this line:

Method #4:

This method is sort of already answered by user8167727 but I disagree with the code they made. It will be using the function is_pressed but in an other way:

import keyboard while True: if keyboard.is_pressed("p"): print("You pressed p") break 

It will break the loop as p is pressed.

As OP mention about raw_input — that means he want cli solution. Linux: curses is what you want (windows PDCurses). Curses, is an graphical API for cli software, you can achieve more than just detect key events.

This code will detect keys until new line is pressed.

import curses import os def main(win): win.nodelay(True) key="" win.clear() win.addstr("Detected key:") while 1: try: key = win.getkey() win.clear() win.addstr("Detected key:") win.addstr(str(key)) if key == os.linesep: break except Exception as e: # No input pass curses.wrapper(main) 

For Windows you could use msvcrt like this:

 import msvcrt while True: if msvcrt.kbhit(): key = msvcrt.getch() print(key) # just to show the result 

Use this code for find the which key pressed

from pynput import keyboard def on_press(key): try: print('alphanumeric key pressed'.format( key.char)) except AttributeError: print('special key pressed'.format( key)) def on_release(key): print(' 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() 

Use PyGame to have a window and then you can get the key events.

For the letter p :

import pygame, sys import pygame.locals pygame.init() BLACK = (0,0,0) WIDTH = 1280 HEIGHT = 1024 windowSurface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) windowSurface.fill(BLACK) while True: for event in pygame.event.get(): if event.key == pygame.K_p: # replace the 'p' to whatever key you wanted to be pressed pass #Do what you want to here if event.type == pygame.locals.QUIT: pygame.quit() sys.exit() 

So I made this ..kind of game.. based on this post (using msvcr library and Python 3.7).

The following is the «main function» of the game, that is detecting the keys pressed:

# Requiered libraries - - - - import msvcrt # - - - - - - - - - - - - - - def _secret_key(self): # Get the key pressed by the user and check if he/she wins. bk = chr(10) + "-"*25 + chr(10) while True: print(bk + "Press any key(s)" + bk) #asks the user to type any key(s) kp = str(msvcrt.getch()).replace("b'", "").replace("'", "") # Store key's value. if r'\xe0' in kp: kp += str(msvcrt.getch()).replace("b'", "").replace("'", "") # Refactor the variable in case of multi press. if kp == r'\xe0\x8a': # If user pressed the secret key, the game ends. # \x8a is CTRL+F12, that's the secret key. print(bk + "CONGRATULATIONS YOU PRESSED THE SECRET KEYS!\a" + bk) print("Press any key to exit the game") msvcrt.getch() break else: print(" You pressed:'", kp + "', that's not the secret key(s)\n") if self.select_continue() == "n": if self.secondary_options(): self._main_menu() break 

If you want the full source code of the porgram you can see it or download it from here:

(note: the secret keypress is: Ctrl + F12 )

I hope you can serve as an example and help for those who come to consult this information.

This is from the openCV package. It detects a keypress without waiting.

You don’t mention if this is a GUI program or not, but most GUI packages include a way to capture and handle keyboard input. For example, with tkinter (in Py3), you can bind to a certain event and then handle it in a function. For example:

import tkinter as tk def key_handler(event=None): if event and event.keysym in ('s', 'p'): 'do something' r = tk.Tk() t = tk.Text() t.pack() r.bind('', key_handler) r.mainloop() 

With the above, when you type into the Text widget, the key_handler routine gets called for each (or almost each) key you press.

I would suggest you use PyGame and add an event handle.

Источник

How to Detect Keypress in Python

While creating programs that run with graphical user interfaces, we need to detect if the user has pressed a key or not several times. In this article, we will see how we can detect keypress in Python.

Detect Keypress Using the keyboard Module in Python

To detect keypress in Python, we can use the keyboard module. It works on both Windows and Linux operating systems and supports all the hotkeys. You can install the keyboard module in your machine using PIP as follows.

If you are working with Python 3, you can install the keyboard module using the following command.

Detect Keypress Using the is_pressed() function in Python

To detect the keypress in Python, we will use the is_pressed() function defined in the keyboard module. The is_pressed() takes a character as input and returns True if the key with the same character is pressed on the keyboard. Therefore, we can use the is_pressed() function with a while loop to detect keypress as shown in the following example.

import keyboard while True: if keyboard.is_pressed("a"): print("You pressed 'a'.") break 

Here, we have executed the while loop until the user presses the key “ a ”. On pressing other keys, the is_pressed() function returns False , and the while loop keeps executing. Once the user presses “a”, the condition inside if block becomes true and the break statement is executed. Hence the while loop terminates.

Keypress using the read_key() Function

Instead of the is_pressed() function, we can use the read_key() function to detect the keypress in Python. The read_key() function returns the key pressed by the user. We can use the read_key() function with a while loop to check whether the user presses a specific key or not as follows.

import keyboard while True: if keyboard.read_key() == "a": print("You pressed 'a'.") break

In the above example, if the user presses the key “a”, the read_key() method returns the character “a”. Hence, the statement inside the if block becomes True and the execution moves out of the while loop using the break statement. Otherwise, the program keeps waiting for the user to press the correct key.

Detect Keypress Using the wait() Function

We can also detect keypress using the wait() function defined in the keyboard module. The wait() function takes a character as input. Upon execution of the wait() method, the execution of the program is paused until the user presses the key passed as an input argument to the function. Once the user presses the correct key, the function stops its execution.

You can observe this in the following example.

import keyboard keyboard.wait("a") print("You pressed 'a'.") 

In this example, we have passed the character “a” to the wait() method. Hence, the wait() method halts the execution of the program until the user presses the key “a”. Once the correct key is pressed, the execution of the program moves ahead and the print statement is executed.

Conclusion

In this article, we have discussed different ways to detect keypress in Python using the keyboard module. To learn more about inputs, you can read this article on getting user input from keyboard in Python. You might also like this article on string concatenation in Python.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Источник

How to detect which key is pressed in Python – Keypress detection in Python

This tutorial is on key press detection in Python. Today we are going to learn how to detect key press in Python. I am not talking about only the detection of a key press, we will also learn how to detect which key is pressed in Python.

Detect which key is pressed in Python

Here we are going to provide a Python program to detect which key is pressed. The program will work as below:

  • After running the program, you can press any key.
  • In the terminal, the program will tell you which key is pressed using the keyboard.

Python Program to detect key press:

import msvcrt while True: if msvcrt.kbhit(): key_stroke = msvcrt.getch() print(key_stroke) # will print which key is pressed
$ python CodeSpeedy.py b'p' b'8' b'6' b'1' b'/' b']

detect which key is pressed in Python

Output: detect which key is pressed in Python

After the small b, in between the single quotes, the pressed key is shown.

Here you can see that we are using msvcrt module which is a module of windows. Though I am not sure if it will work on Linux or not. It has been tested on Windows and it works fine for me.

There are other ways too to detect keypress in Python. But I personally like this one.

Feel free to let us know if you find a better way to do this in the below comment section.

Источник

Оцените статью