You can use Keyboard module to detect keys pressed. It can be installed by using pip. You can find the documentation here. Keyboard API docs

pip install keyboard

check the below code to understand how it can be done.

import sys
import keyboard
a=[1,2,3,4]
print("Press Enter to continue or press Esc to exit: ")
while True:
    try:
        if keyboard.is_pressed('ENTER'):
            print("you pressed Enter, so printing the list..")
            print(a)
            break
        if keyboard.is_pressed('Esc'):
            print("\nyou pressed Esc, so exiting...")
            sys.exit(0)
    except:
        break

Output:

Answer from Murali on Stack Overflow
🌐
PyPI
pypi.org › project › keyboard
keyboard · PyPI
import keyboard keyboard.press_and_release('shift+s, space') keyboard.write('The quick brown fox jumps over the lazy dog.') keyboard.add_hotkey('ctrl+shift+a', print, args=('triggered', 'hotkey')) # Press PAGE UP then PAGE DOWN to type "foobar". keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar')) # Blocks until you press esc.
      » pip install keyboard
    
Published   Mar 23, 2020
Version   0.13.5
Discussions

Stop the execution of input() if ESC is pressed
You'll need the "keyboard" library, and then you need to move your program execution to a loop that looks for an escape key. More on reddit.com
🌐 r/learnpython
4
2
May 8, 2023
windows - How to detect ESCape keypress in Python? - Stack Overflow
I am running a process in a command window (Windows 7, Python 3.1) where I would like the user to abort the process by pressing Esc key. However, pressing Esc doesn't appear to do anything, the loop More on stackoverflow.com
🌐 stackoverflow.com
Using keyboard in my program
Hi guys, I’m new to python and today I want to add keyboard support to my program, namely the ability to exit the program by pressing ‘esc’, but it’s isn’t work, a screenshot will tell you more about it. More on discuss.python.org
🌐 discuss.python.org
0
0
June 2, 2023
keyboard - Press esc to stop and any other key to continue in Python - Stack Overflow
Now with help of raw_input, I can call a method every time user presses Enter. if __name__ == '__main__': while True: raw_input("Press Enter to continue...") _start() def _star... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnpython › stop the execution of input() if esc is pressed
r/learnpython on Reddit: Stop the execution of input() if ESC is pressed
May 8, 2023 -

As the title suggests, I have some code that looks like this (overly simplified):

x = input("question")

I want to be able to break out of this input if the user simply presses escape. I am not sure if I would need to change the function I use to get the input that allows key presses.

Ideally, I would want the code to return 0 at anytime that escape is pressed.

🌐
Python.org
discuss.python.org › python help
Using keyboard in my program - Python Help - Discussions on Python.org
June 2, 2023 - Hi guys, I’m new to python and today I want to add keyboard support to my program, namely the ability to exit the program by pressing ‘esc’, but it’s isn’t work, a screenshot will tell you more about it.
🌐
PyAutoGUI
pyautogui.readthedocs.io › en › latest › keyboard.html
Keyboard Control Functions — PyAutoGUI documentation
To press these keys, call the press() function and pass it a string from the pyautogui.KEYBOARD_KEYS such as enter, esc, f1.
🌐
Read the Docs
pynput.readthedocs.io › en › latest › keyboard.html
Handling the keyboard — pynput 1.7.6 documentation
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() # ...or, in a non-blocking fashion: listener = keyboard.Listener( on_press=on_press, on_release=on_release) listener.start() A keyboard listener is a threading.Thread, and all callbacks will be invoked from the thread.
Find elsewhere
🌐
The Python Code
thepythoncode.com › article › control-keyboard-python
Keyboard module: Controlling your Keyboard in Python - The Python Code
keyboard.write("Python Programming is always fun!", delay=0.1) Setting the delay to 0.1 indicates 0.1 seconds to wait between key presses; this will look fancy, like in hacking movies! You can do many more cool things with this module, such as recording keyboard events using record() function and playing them again using play() function: # record all keyboard clicks until esc is clicked events = keyboard.record('esc') # play these events keyboard.play(events) I passed 'esc' to record() method to record key presses and releases until I press the 'esc' button, and then we play these events again using the play() method.
🌐
Nitratine
nitratine.net › blog › post › simulate-keypresses-in-python
Simulate Keypresses In Python - Nitratine
December 16, 2017 - keyboard.press(Key.ctrl) keyboard.press('c') keyboard.release('c') keyboard.release(Key.ctrl) Here are a few other common special keys: Key.alt_l: Left ALT · Key.backspace: Backspace · Key.ctrl_l: Left Ctrl · Key.delete: Delete · Key.enter: Enter · Key.esc: Escape ·
🌐
GitHub
github.com › PySimpleGUI › PySimpleGUI › issues › 2023
[Question] How do I detect when the Escape key has been pressed? · Issue #2023 · PySimpleGUI/PySimpleGUI
September 26, 2019 - import PySimpleGUI as Sg font_normal = 'SourceSans', 11 fg = '#aaaaaa' bg = '#121212' settings_layout = [ [Sg.Text(f'Bug catcher by Elijah Lopez', text_color=fg, background_color=bg, font=font_normal)] ] settings_window = Sg.Window('Settings', settings_layout, background_color=bg, return_keyboard_events=True, use_default_focus=False) settings_window.Finalize() settings_window.TKroot.focus_force() a = True settings_event = '' while settings_event is not None: settings_event, settings_values = settings_window.Read() if settings_event != '__TIMEOUT__': print(settings_event) when I press "Esc" I see a white box in my console.
Author   elibroftw
🌐
pytz
pythonhosted.org › pynput › keyboard.html
Handling the keyboard — pynput 1.1.2 documentation
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() A keyboard listener is a threading.Thread, and all callbacks will be invoked from the thread.
🌐
PsychoPy
discourse.psychopy.org › coding
Pressing ESC key at any moment to end the experiment - Coding - PsychoPy
October 31, 2016 - Hello, I’ve build an experiment which goes through many phases and loops. However, I would like to be able to press the “ESC” key at any given moment while the experiment is running in order to close the window and end the experiment. I’m aware that I could use this chunk of code: while True: keys = event.getKeys() if keys: if keys[0] == 'Esc': win.close() core.quit() However, I would have to add this bit of code it to every loop an...
🌐
Delft Stack
delftstack.com › home › howto › python › python detect keypress
How to Detect Keypress in Python | Delft Stack
February 12, 2024 - However, in our function, we only take action on key press events. The last line, keyboard.wait('esc'), is crucial as it keeps our script running and waits until the escape key (ESC) is pressed.
🌐
Reddit
reddit.com › r/learnpython › i need help with ending a program when a key is pressed
r/learnpython on Reddit: I need help with ending a program when a key is pressed
February 2, 2019 -

Hi everyone. I want to make a program that will minimize the foreground window every 10 seconds, and it ends when I press a specific key (for example, the escape key). I found a module called pynput that allows you to listen for keypresses, which is what I want to do because I want to listen for the key system wide even if the python console window is not the window in focus. Here is how listening for that key is done using pynput:

from pynput import keyboard

def on_release(key):
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# Collect events until released
with keyboard.Listener(on_release=on_release) as listener:
    listener.join()

Now, I'm a beginner, so I don't 100% understand this code that I've put here, as it is a portion of an example given in the documentation for using the module. This snippet of code works as intended (ending the program when escape is pressed). The problem I have is I don't know how to actually have this listen while other stuff happens somewhere else in a loop (the window minimizing every 10 seconds). Does anyone have any suggestions on how I could make something like this work? Or even suggestions on a different method of listening for a keypress, if there is some better way? Thanks in advance!

Top answer
1 of 1
1
If you want to do 2 things at once, 1) listen for keypress 2) do other stuff, you have to use something like multiprocessing. The problem is that you have to jump through hoops to get input from the console in a Process, so this uses a GUI, Tkinter, which is set up to get something separately. This is canned code from my toolbox. It runs 2 separate infinite loop Processes until the quit button is pressed. In this example, if the Process finished before the button is clicked, the program continues to run. It only exits when the button is clicked. import sys if 3 == sys.version_info[0]: ## 3.X is default if dual system import tkinter as tk ## Python 3.x else: import Tkinter as tk ## Python 2.x import time from multiprocessing import Process class TestClass(): def test_f(self, spaces=1): """ a counter is used to simulate something going in the background """ ctr = 0 while True: print(" "*spaces, ctr) ctr += 1 time.sleep(1.0) def tk_quit(self): """ this function just waits for a button click and then exits/returns, allowing the rest of this program to execute """ root=tk.Tk() tk.Button(root, text="Quit", command=root.quit, width=10).grid() root.mainloop() if __name__ == '__main__': ## run function in the background CT=TestClass() ## start as many processes as you want p1 = Process(target=CT.test_f) p1.start() p2 = Process(target=CT.test_f, args=(10,)) p2.start() CT.tk_quit() print("terminate process") for p in [p1, p2]: if p.is_alive(): p.terminate() p.join()
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 › python › keyboard-module-in-python
Keyboard module in Python - GeeksforGeeks
April 12, 2025 - A second hotkey (ctrl + shift + a) prints a message when pressed. keyboard.wait('esc') pauses the program until the 'Esc' key is pressed, terminating the program.