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 ...

Discussions

How to detect any key pressed without blocking execution in Python - Stack Overflow
I have an script that checks the position of the mouse every 60 seconds. If the mouse has not moved, it moves it, makes a right click, clicks esc, and sleeps. It is pretty handy to avoid the computer More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Detect Keypress without blocking - Stack Overflow
I want to detect when the user presses the RETURN/ENTER key. Right now, I am doing this using a while loop, but that blocks my code unless the while is broken. Is there any way to detect the ENTER... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python 3.x - Detect (non-blocking) key press while accepting client connections - Stack Overflow
I am fairly new at programming in python. I am trying to code some form of simulation using sockets. I am able connect multiple clients to the server successfully. However I would like the server to More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to detect key presses? - Stack Overflow
Ugly as anything but still more beautiful then anything else I've seen. The weird thing is I remember distinctly back in my python2.7 days opening file descriptor 0 (stdin) for read with non-blocking and having it behave itself as a keypress collector, but for the life of me I can't figure ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
PythonForBeginners.com
pythonforbeginners.com โ€บ home โ€บ how to detect keypress in python
How to Detect Keypress in Python - PythonForBeginners.com
June 30, 2023 - Hence the while loop terminates. 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.
๐ŸŒ
Google Groups
groups.google.com โ€บ g โ€บ comp.lang.python โ€บ c โ€บ dldnjWRX3lE
Why doesn't Python include non-blocking keyboard input function?
By non-blocking you mean checking if a key has been pressed rather than waiting for it to be pressed? I use the latter ALL THE TIME when debugging. The former less often, because if I wanted to use it to abort huge amounts of output, I just abort the program (with Ctrl Break). Nevertheless, it is still used sometimes, and it's there when I need it (NOT Python): repeat print "A" until testkey()
๐ŸŒ
Shallow Thoughts
shallowsky.com โ€บ blog โ€บ programming โ€บ python-read-characters.html
Reading keypresses in Python (Shallow Thoughts)
But after a few hours of fiddling and googling, I realized that even if Python's termios can't block, there are other ways of blocking on input. The select system call lets you wait on any file descriptor until has input. So I should be able to set stdin to be non-blocking, then do my own blocking by waiting for it with select.
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
๐ŸŒ
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. Any ideas on what to try? ... I get the same error when running your code from Idle3. However, if you run your code from a terminal it does not produce this error but the test for x>0 generates an error as x is not an integer.
๐ŸŒ
Wordpress
techdevops.wordpress.com โ€บ 2015 โ€บ 03 โ€บ 24 โ€บ non-blocking-io-keyboard-listener-in-python
Non Blocking IO / Keyboard Listener in Python โ€“ Technology, Development & Operations
March 24, 2015 - Hi all, I will show you how to create a simple keyboard listener (non blocking IO you can say) in python. This will however work only on Linux and not windows systems. For windows, best way is to use Threads which we will discuss sometime later. OUTPUT: Understanding Code: We have used "select" ...
Find elsewhere
๐ŸŒ
Raspberry Pi Forums
forums.raspberrypi.com โ€บ board index โ€บ programming โ€บ python
Check for keypad character without stopping? - Raspberry Pi Forums
I would switch to Thony - it seems to be the choice going forward for Python 3 according to the local Jam meeting but it may well have the same problem. I find the highlighting helps my editing and then I just flip to a terminal and run from there if needed.
๐ŸŒ
Oulub
oulub.com โ€บ en-US โ€บ Python โ€บ faq.windows-how-do-i-check-for-a-keypress-without-blocking
How do I check for a keypress without blocking? - Python... - Multilingual Manual - OULUB
Use the msvcrt module. This is a standard Windows-specific extension module. It defines a function kbhit() which checks whether a keyboard hit is present, and getch() which gets one character without echoing it.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 55074077 โ€บ detect-non-blocking-key-press-while-accepting-client-connections
python 3.x - Detect (non-blocking) key press while accepting client connections - Stack Overflow
Else it keeps listening for key presses. import curses, time def keyPress(stdscr): # checking for keypress stdscr.nodelay(True) # do not wait for input when calling getch return stdscr.getch() while True: if curses.wrapper(keyPress) == 97: print("You pressed 'a'") else: pass time.sleep(0.1)
๐ŸŒ
Java2Blog
java2blog.com โ€บ home โ€บ python โ€บ detect keypress in python
Detect keypress in Python - Java2Blog
June 12, 2021 - The kbhit() function waits for a key to be pressed and returns True when it is pressed. The getch() function returns the key pressed in a byte string. Notice the b in the output. The break statement will come out of this code block.
Top answer
1 of 16
144

Python has a keyboard module with many features. 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('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
2 of 16
114

For those who are on windows and were struggling to find an working answer here's mine: pynput.

Here is the pynput official "Monitoring the keyboard" source code example:

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

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.

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()
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-detect-if-a-specific-key-pressed-using-python
How to detect if a specific key pressed using Python? - GeeksforGeeks
October 13, 2022 - Here we are importing the keyboard Module and with the help of read_key() method checking what key is pressed. ... In this method, we will use pynput Python module to detecting any key press.
๐ŸŒ
Rapidken
rapidken.ai โ€บ python 3 faqs โ€บ python on windows faq โ€บ how do i check for a keypress without blocking?
Annotated - How do I check for a keypress without blocking?
Annotated, easy to learn Python 3: "How do I check for a keypress without blocking?" in "Python 3 Doc FAQs > Python on Windows FAQ > How do I check for a keypress without blocking?"
๐ŸŒ
Read the Docs
pynput.readthedocs.io โ€บ en โ€บ latest โ€บ keyboard.html
Handling the keyboard โ€” pynput 1.7.6 documentation
To simplify scripting, synchronous event listening is supported through the utility class pynput.keyboard.Events. This class supports reading single events in a non-blocking fashion, as well as iterating over all events.
๐ŸŒ
Quora
quora.com โ€บ How-do-you-check-if-a-key-was-pressed-in-Python-Python-Python-3-x-development
How to check if a key was pressed in Python (Python, Python 3.x, development) - Quora
Answer (1 of 2): Oof, this is one of those topics that hits close to home, as I recently wrote a script that needed to read keypresses, and had a hell of a time at it. The biggest problem is thereโ€™s no standard library for doing this in every operating system.