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:

» pip install keyboard
Stop the execution of input() if ESC is pressed
windows - How to detect ESCape keypress in Python? - Stack Overflow
Using keyboard in my program
keyboard - Press esc to stop and any other key to continue in Python - Stack Overflow
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 3 strings are unicode and, therefore, must be encoded to bytes for comparison. Try this test:
if msvcrt.kbhit() and msvcrt.getch() == chr(27).encode():
aborted = True
break
Or this test:
if msvcrt.kbhit() and msvcrt.getch().decode() == chr(27):
aborted = True
break
Or this test:
if msvcrt.kbhit() and ord(msvcrt.getch()) == 27:
aborted = True
break
You don't need encode, decode, chr, ord, ....
if msvcrt.kbhit() and msvcrt.getch() == b'\x1b':
or if you'd like to see "27" in the code somewhere:
if msvcrt.kbhit() and msvcrt.getch()[0] == 27:
you can use pynput,it's easier to use.
from pynput import keyboard
def _start():
print("HelloWorld")
def on_press(key):
if key == keyboard.Key.esc:
# Stop listener
return False
else:
_start()
# Collect events until released
with keyboard.Listener(
on_press=on_press) as listener:
listener.join()
Your best bet is probably go the curses way.
import curses
def main():
stdscr = curses.initscr()
while True:
key = stdscr.getch()
if key == 27: # This is the escape key code
curses.endwin()
break
main()
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!
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
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()
Can I detect user pressing esc key during input without any libraries?
First of all, you forgot to close the strings on lines 4 and 6.
But your main issue is that you call keyboard.read_key() once for each arm of your if statement. This makes your code wait for a keypress, check if it's 'enter', then wait for another keypress, check if it's 'q', and so on.
What you should do is save the key to a variable, then check the variable. It should look something like this:
import keyboard
while True:
key = keyboard.read_key()
if key == 'enter':
print('Enter is pressed')
if key == 'q':
print('Quitting the program')
break
if key == 's':
print('Skiping the things')
As per Keyboard documentation:
Other applications, such as some games, may register hooks that swallow all key events. In this case keyboard will be unable to report events.
One way to solve your problem with keyboard module is keyboard.wait('key')
# Blocks until you press esc
keyboard.wait('esc')
Something work around is as below:
import keyboard
keyboard.wait('enter')
print('Enter is pressed')
keyboard.wait('q')
print('Quitting the program')
keyboard.wait('s')
print('Skiping the things')