You can intercept the ctrl+c signal and call your own function at that time rather than exiting.

import signal
import sys

def exit_func(signal, frame):
    '''Exit function to be called when the user presses ctrl+c.
    Replace this with whatever you want to do to break out of the loop.
    '''
    print("Exiting")
    sys.exit(0) # remove this if you do not want to exit here

# register your exit function to handle the ctrl+c signal
signal.signal(signal.SIGINT, exit_func)

#loop forever
while True:
    ...

You should replace sys.exit(0) with something more useful to you. You could raise an exception and that except on it outside the loop body (or just finally) to perform your cleanup actions.

Answer from Ryan Haining on Stack Overflow
๐ŸŒ
PythonForBeginners.com
pythonforbeginners.com โ€บ home โ€บ how to detect keypress in python
How to Detect Keypress in Python - PythonForBeginners.com
June 30, 2023 - 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 ...
Discussions

How to call a function whenever a key is pressed in python - Stack Overflow
I have a program that is running a loop. Whenever I press, for example, the key "ESC" on keyboard, it should call out a function which prints "You pressed the key ESC" and maybe executes some comma... More on stackoverflow.com
๐ŸŒ stackoverflow.com
October 31, 2013
python - How to detect key presses? - Stack Overflow
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, More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to run a method on keypress in tkinter - Stack Overflow
I have an entry field, and as I type into the data field, I want a method, that updates a treeview widget to be ran. Currently, I can type in a search parameter, then press a 'search' button and it... More on stackoverflow.com
๐ŸŒ stackoverflow.com
user interface - How to execute code with keypress in python 2.7? - Stack Overflow
does anyone know how i can execute code by key press in python 2.7? I'm thinking that maybe i should make an invisible window and on key-press it executes code which i can have under a function? does More on stackoverflow.com
๐ŸŒ stackoverflow.com
July 13, 2014
๐ŸŒ
Pierian Training
pieriantraining.com โ€บ home โ€บ how to wait for a keypress in python
How to Wait for a Keypress in Python - Pierian Training
April 28, 2023 - If you want to wait for a keypress in Python, you can use the `msvcrt` module. This module provides access to a number of functions in the Microsoft Visual C runtime library, including the ability to read a single character from the console. ... In this example, we import the `msvcrt` module and then use its `getch()` function to wait for a keypress. The `getch()` function reads a single character from the console without echoing it to the screen. Once a key is pressed, the program continues execution and prints โ€œContinuingโ€ฆโ€ to the console.
๐ŸŒ
Nitratine
nitratine.net โ€บ blog โ€บ post โ€บ simulate-keypresses-in-python
Simulate Keypresses In Python - Nitratine
December 16, 2017 - Import Key and Controller from pynput.keyboard. ... Make a variable called keyboard and set it to an instance of Controller. Now using the keyboard variable we can press and release keys.
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()
๐ŸŒ
Raspberry Pi Forums
forums.raspberrypi.com โ€บ board index โ€บ programming โ€บ python
Detect keypress in Python in a simple way? - Raspberry Pi Forums
from tkinter import * def keydown(e): print( e.char ) root = Tk() frame = Frame(root, width=100, height=100) lbl = Label(frame, text="Press a key") lbl.pack() frame.bind("<KeyPress>", keydown) frame.pack() frame.focus_set() root.mainloop() This displays a window which waits for keypresses, and displays the key pressed on the console. ... The keyboard library does indeed require sudo permissions. From their "Known Limitations" list: To avoid depending on X, the Linux parts reads raw device files (/dev/input/input*) but this requires root.
Find elsewhere
๐ŸŒ
YouTube
youtube.com โ€บ watch
Python - Hot Keys - Run Code With Keyboard Key Press - YouTube
In Python we take a look on creating hotkeys inside python to run your code when you need by just using your hand on a keyCODE: https://pastebin.com/9c1LFKTU
Published ย  February 1, 2022
๐ŸŒ
Tech with Tim
techwithtim.net โ€บ tutorials โ€บ python-module-walk-throughs โ€บ turtle-module โ€บ key-presses-events
Python Turtle Tutorial - Key Presses & Events
import turtle import random def up(): tim.setheading(90) tim.forward(100) def down(): tim.setheading(270) tim.forward(100) def left(): tim.set_heading(180) tim.forward(100) def right(): tim.setheading(0) tim.forward(100) tim.listen() tim.onkey(up, "Up") # This will call the up function if the ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 55657689 โ€บ how-to-run-a-method-on-keypress-in-tkinter
python - How to run a method on keypress in tkinter - Stack Overflow
bind does more than bind to one key at a time. You can use it to bind to any key press or key release. ... from Tkinter import * def keyup(e): pass; # e.char contains the pressed key if you need that info # use your search function here
๐ŸŒ
PyAutoGUI
pyautogui.readthedocs.io โ€บ en โ€บ latest โ€บ keyboard.html
Keyboard Control Functions โ€” PyAutoGUI documentation
The primary keyboard function is write(). This function will type the characters in the string that is passed. To add a delay interval in between pressing each character key, pass an int or float for the interval keyword argument. ... >>> pyautogui.write('Hello world!') # prints out "Hello ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 24717859 โ€บ how-to-execute-code-with-keypress-in-python-2-7
user interface - How to execute code with keypress in python 2.7? - Stack Overflow
July 13, 2014 - For key availabe in all system you will have to register this key in system or read keys directly from system - and it depends on system ... Look for some keylogger in Python - it knows how to grap pressed key.
๐ŸŒ
Code Today
codetoday.co.uk โ€บ post โ€บ how-to-pass-the-key-pressed-to-the-function-when-using-onkeypress-in-python-s-turtle-module
How to pass the key pressed to the function when using onkeypress in Python's turtle module
February 1, 2024 - You've created an instance of the Screen() and the Turtle() objects, defined a function that draws a square and then used onkeypress() to bind the space bar key to this function. So when you run the program and press space, the turtle will draw a square.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python detect keypress
How to Detect Keypress in Python | Delft Stack
February 12, 2024 - The on_release function prints out which key was released, and if the escape key is pressed, it returns False, which stops the listener from listening to more key events. The keyboard.Listener is used as a context manager that starts the listening process. The listener.join() method is called to wait until the listener stops, which happens when the escape key is pressed. ... While there are multiple methods to capture key inputs in Python, the readchar library offers a simple and efficient way to detect single keypresses.
๐ŸŒ
Java2Blog
java2blog.com โ€บ home โ€บ python โ€บ detect keypress in python
Detect keypress in Python - Java2Blog
June 12, 2021 - 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. If it is removed, then the code will keep on executing.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-detect-if-a-specific-key-pressed-using-python
How to detect if a specific key pressed using Python? - GeeksforGeeks
July 23, 2025 - Define functions ยท For installation run this code into your terminal. pip install pynput ยท Example 1: Here you will see which key is being pressed. Python3 ยท from pynput.keyboard import Key, Listener def show(key): print('\nYou Entered {0}'.format( key)) if key == Key.delete: # Stop listener return False # Collect all event until released with Listener(on_press = show) as listener: listener.join() Output: Example 2: Here you can detect a specific key is being been pressed or not.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 68930510 โ€บ how-to-make-script-run-when-key-pressed
python - How to make script run when key pressed? - Stack Overflow
I am trying to create a small bit of code that will print the integer stored in the variable 'money' when the m key is pressed. To show what I mean, here is a bit of the code. I know this is nowher...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 51217478 โ€บ how-to-make-python-execute-a-command-when-a-key-is-detected-to-be-pressed
keyboard - How to make Python execute a command when a key is detected to be pressed - Stack Overflow
Or maybe to make Python not wait for enter to be pressed? ... @JamesRogers you've already said that. However, this is not enough detail. This problem can be understood in different ways, and I had three guesses in the comment above. ... Save this answer. Show activity on this post. Assuming you don't need this to work when the window is not in focus, you should use getch from msvcrt to react to the keypresses immediately and then if and elif to distinguish the keys.
๐ŸŒ
Nitratine
nitratine.net โ€บ blog โ€บ post โ€บ how-to-make-hotkeys-in-python
How to Make Hotkeys in Python - Nitratine
January 13, 2018 - from pynput import keyboard def function_1(): print('Function 1 activated') def function_2(): print('Function 2 activated') with keyboard.GlobalHotKeys({ '<alt>+<ctrl>+r': function_1, '<alt>+<ctrl>+t': function_1, '<alt>+<ctrl>+y': function_2}) as h: h.join() In this example, keyboard.HotKey.parse is being used in the background by keyboard.GlobalHotKeys. Did you install pynput? This error will not occur if you installed it properly. If you have multiple versions of Python, make sure you are installing pynput on the same version as what you are running the script with.
๐ŸŒ
Nitratine
nitratine.net โ€บ blog โ€บ post โ€บ how-to-detect-key-presses-in-python
How to Detect Key Presses In Python - Nitratine
April 7, 2020 - def on_press(key): logging.info("Key pressed: {0}".format(key)) def on_release(key): logging.info("Key released: {0}".format(key)) Now when the script is run, nothing should be printed to the console. This is because it is all being saved to the file declared in the basic configuration. Save and close IDLE. Open the file named key_log.txt next to your python script; all the events should be logged in here.