The standard approach is to use the select module.

However, this doesn't work on Windows. For that, you can use the msvcrt module's keyboard polling.

Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device.

Answer from S.Lott on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › non-blocking terminal input python
r/learnpython on Reddit: non-blocking terminal input Python
March 2, 2020 -

I want to write a simple program in the terminal that takes in non-blocking I/O input basically. The idea as as follows (it's very simple):

while True: 
    print("#"*length_bar)
    if keypress: # runs in "background" or concurrent with main loop
        length_bar += 1

Now, the problem is that I have trouble finding a way to get non-blocking keyboard input from the user while print stuff in the terminal as well. I want this bar to continuously print while waiting actively for board input. Been banging my head against this devilishly simple problem for an hour or so now but can't seem to find a satisfactory answer on google or stackoverflow ...

🌐
Reddit
reddit.com › r/learnpython › is there a way to detect keyboard presses without using "keyboard" or "pynput"? (explanation inside)
r/learnpython on Reddit: Is there a way to detect keyboard presses without using "keyboard" or "pynput"? (explanation inside)
January 9, 2023 -

I need to detect keyboard presses in a python3 script running on a headless linux server (Unbuntu).

I can't use pynput because that relies on X, which doesn't exist.

I can't use keyboard, because for some inexplicable reason, it crashes rtmidi, the library I use for reading midi input. Why? No idea. I just add one line of code like "keyboard.wait" and rtmidi crashes with this error:

TypeError: 'tuple' object is not callable
Exception ignored in: 'rtmidi._rtmidi._cb_func'

So now I'm stuck. Any ideas?

🌐
Reddit
reddit.com › r/learnpython › how to detect a keypress when the program is running?
r/learnpython on Reddit: How to detect a keypress when the program is running?
October 1, 2021 -

I have a program which takes user input and outputs an answer. Now, I'd like to make it so that when the user presses a certain key, it exits the program. But how can you make it so that the program tries to detect that exit keypress at all times? Even when its looking for a user input?

I am only able to do one step at a time, like user input/output, then exit, or I can put exit first but that will just exit before anything happens

Thanks in advance!

🌐
PythonForBeginners.com
pythonforbeginners.com › home › how to detect keypress in python
How to Detect Keypress in Python - PythonForBeginners.com
June 30, 2023 - ... 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.
🌐
Google Groups
groups.google.com › g › comp.lang.python › c › dldnjWRX3lE
Why doesn't Python include non-blocking keyboard input function?
> It doesn't even imply it, technically - > you could want to do other stuff and occasionally check if the user has > entered a line, though *that* is even *more* involved on Windows because > it means you can't do it with msvcrt.kbhit. ... Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... jlad...@itu.edu writes: > ... I find myself asking why Python doesn't include a standard, > non-blocking keyboard input function.
🌐
Shallow Thoughts
shallowsky.com › blog › programming › python-read-characters.html
Reading keypresses in Python (Shallow Thoughts)
If I read a character with c = sys.stdin.read(1) but there's been no character typed yet, a non-blocking read will throw an IOError exception, while a blocking read will wait, not returning until the user types a character. In the code on that Python FAQ page, blocking looks like it should be optional.
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › how to detect keypress in python? without wait the user to press any key
r/learnpython on Reddit: How to detect keypress in Python? Without wait the user to press any key
May 23, 2020 -

I need to detect if any key is pressed but i cannot wait until the user press anything

Like he only gonna press any key if he wants to stop the program,so the program need to continue while he dont press nothing

Ps:sorry my bad english

from datetime import datetime
import os
from msvcrt import getch
from time import sleep

def get_down(time):
    print('press ENTER to cancel \n')
    while True:
        key = ord(getch())    #the program stop wanting the user to press a key
        if key == 13:
            print('You cancel the operation')
            break

        if time == hours:
            print("The system is gonna turn off")
            sleep(5)
            os.system("shutdown /s /t 1")


hours = datetime.now().strftime('%H:%M')
print('Now is: {}'.format(hours))
get_down(str(input('When you want to shutdown? (hh:mm):')))
🌐
Reddit
reddit.com › r/learnpython › way to detect keypress in python without importing any libraries? (x-post from /r/python)
r/learnpython on Reddit: Way to detect keypress in Python without importing any libraries? (X-post from /r/python)
September 1, 2015 -

I'm trying to create a platformer in Python 3.4.3 on OS X. Unfortunately, using event.key with Pygame doesn't return anything but 0 for the letter keys. It works for the arrow keys:

IF event.key == pygame.K_DOWN: returns a value if the down key is pressed.

But not for WASD:

IF event.key == pygame.K_s: does not return a value if the s key is pressed, no matter what modifiers are active.

And using the curses library gives me a terminal error when I initialize it.

Is there any way to detect keycodes without importing a library?

Top answer
1 of 1
3

You can use method #3 of https://stackoverflow.com/a/57644349/9997212:

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:

keyboard.unhook_all()

This will allow your program to be event-oriented and will not block your main thread.

To listen to all keys instead of a specific one, use keyboard.hook. It works the same way:

import keyboard

keyboard.hook(lambda event: print(f'You pressed {event.name}'))

The key is to set up a global variable as a boolean. The hook works as an interrumption, therefore, everytime that it is triggered, you activate as True the boolean. After the check that you need you turn it back to False. Something like this:

import keyboard

try: #the try, finally is used to activate and relase the hooks to the keyboard
        
        def handle_key(event):
            global KeyPressed #the almighty global variable that monitors whether the keyboard was pressed or not.
            
            KeyPressed = True
            # print("KeyPressed is now:", event.name) #in case you want to know what did you pressed.
            return 
        
        global KeyPressed #the almighty global variable that monitors whether the keyboard was pressed or not.
        
        KeyPressed = False #initialize as False, no key was touched

        keyboard.hook(lambda event: handle_key(event) ) #this activates the detection of pressed keys. Must end with "keyboard.unhook_all()"

        if not KeyPressed: #means you have not pressed a key
            do_something()
                
        else: #Then a key was pressed
            KeyPressed = False #reset the pressed state to False
                    
        sleep(PAUSE) #wait the specified pause
finally:
        keyboard.unhook_all() #this resets the "keyboard.hook(lambda event: handle_key(event) )" so that no more keys are registered
🌐
Java2Blog
java2blog.com › home › python › detect keypress in python
Detect keypress in Python - Java2Blog
June 12, 2021 - To detect keypress, we can use a few functions from this module. The read_key() function from this module is used to read the key pressed by the user. We can check whether the pressed key matches our specified key.
🌐
Reddit
reddit.com › r/learnpython › how do i detect any keypress?
r/learnpython on Reddit: How do i detect any keypress?
March 21, 2023 -

So i am trying to make an AFK mouse mover for testing purposes and i saw online people used "keyboard". However, almost every tutorial i saw needed a specific key, and i want ANY key, be it space, windows key, a, b, enter, whatever...Here is my code (sorry if it's garbage, i'm still learning a lot). It gives out an error:

TypeError: is_pressed() missing 1 required positional argument: 'hotkey'

What do i need to do?

import pyautogui as pag
import time as time
import random as random
import keyboard as keyboard


cur_cords = pag.position()
afk_counter = 0

def move_mouse():
    while True:
        global cur_cords
        global afk_counter
        if pag.position() == cur_cords and keyboard.is_pressed() == False:
            afk_counter += 1
        else:
            afk_counter = 0
            cur_cords = pag.position()
        if afk_counter > 5:
            x = random.randint(1, 2560)
            y = random.randint(1, 1440)
            pag.moveTo(x, y, 0.5)
            cur_cords = pag.position()
            print(f"AFK counter timer: {afk_counter}")
        time.sleep(2)

move_mouse()
Top answer
1 of 2
1
Maybe read_key or read_hotkey ?
2 of 2
1
Try this import pyautogui import time import random import keyboard def on_key_press(key_pressed): """ Update the value of key_pressed to True when any key is pressed. Args: key_pressed (list): A list containing a boolean value. Returns: None """ key_pressed[0] = True def move_mouse(cur_cords, afk_counter): """ Move the mouse cursor randomly when the mouse is idle and no key is pressed. Args: cur_cords (tuple): A tuple representing the current coordinates of the mouse cursor. afk_counter (list): A list containing an integer value representing the time since the mouse cursor was last moved. Returns: tuple: A tuple containing the updated values of cur_cords and afk_counter. """ # Initialize the key_pressed list with a value of False. key_pressed = [False] # Call the on_key_press function whenever any key is pressed. keyboard.on_press(lambda event: on_key_press(key_pressed)) # Move the mouse cursor randomly when the mouse is idle and no key is pressed. while True: if pyautogui.position() == cur_cords and not key_pressed[0]: afk_counter[0] += 1 else: afk_counter[0] = 0 cur_cords = pyautogui.position() key_pressed[0] = False if afk_counter[0] > 5: x = random.randint(1, 2560) y = random.randint(1, 1440) pyautogui.moveTo(x, y, 0.5) cur_cords = pyautogui.position() print(f"AFK counter timer: {afk_counter[0]}") time.sleep(2) return cur_cords, afk_counter if __name__ == '__main__': # Get the current coordinates of the mouse cursor and initialize the afk_counter list with a value of 0. cur_cords = pyautogui.position() afk_counter = [0] # Call the move_mouse function with the initial values of cur_cords and afk_counter. move_mouse(cur_cords, afk_counter)
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
Check for keypad character without stopping? - Raspberry Pi Forums
All I need to do is get a single keypress from the Pi's keyboard, check it is in-range, if it is, look up the GPIO port pin numbers to blip to press the equivalent key on the target system. Amazingly, the hardest part of all this is proving to be the bit where I read a character (if any) from ...
🌐
Reddit
reddit.com › r/learnpython › stopping an infinite loop with a keypress without being root?
r/learnpython on Reddit: Stopping an infinite loop with a keypress without being root?
May 19, 2024 -

I have a python script which needs to run an infinite loop until the user presses "q", but it also needs to be able to do stuff within the loop. I found some excellent looking code at https://www.reddit.com/r/learnpython/comments/zwz0k9/comment/j1yakmx/ however it appears the keyboard Python module requires you to be root in order to use it, which is not suitable for my use case.

For ease of viewing here's a slightly modified version of the code from the other post:

import time
import keyboard
import threading
import queue


def look_for_key(keys: list[str], q: queue.Queue, done: threading.Event):
  while not done.is_set():
    for key in keys:
      if keyboard.is_pressed(key):
        q.put_nowait(key)


done = threading.Event()
q = queue.Queue()
look_thread = threading.Thread(target=look_for_key, args=(['q'], q, done))
look_thread.start()

big_loop = True
while big_loop:
  # Do stuff here


  while not q.empty():
    key = q.get_nowait()
    if key == "q":  # check if the Q key is pressed
      big_loop = False
      done.set()
      break # exit the loop

look_thread.join()

Can anyone suggest a way of achieving this that doesn't require root permissions on Linux?

EDIT: I tried using pynput as this looked promising, but it requires an X server apparently.

🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
Non-blocking keyboard input in Python 3 - Raspberry Pi Forums
) When I run this code I get the following error: Traceback (most recent call last): File "/home/pi/MJH/KeyIn Test.py", line 2, in <module> stdscr = curses.initscr() File "/usr/lib/python3.4/curses/__init__.py", line 30, in initscr fd=_sys.__stdout__.fileno()) _curses.error: setupterm: could not find terminal I assume this is a common procedure but I cannot seem to find the solution online.