Python, Press Any Key To Exit
This syntax error is caused by using input
on Python 2, which will try to eval
whatever is typed in at the terminal prompt. If you've pressed enter then Python will essentially try to eval an empty string, eval("")
, which causes a SyntaxError
instead of the usual NameError
.
If you're happy for "any" key to be the enter key, then you can simply swap it out for raw_input
instead:
raw_input("Press Enter to continue")
Note that on Python 3 raw_input
was renamed to input
.
For users finding this question in search, who really want to be able to press any key to exit a prompt and not be restricted to using enter, you may consider to use a 3rd-party library for a cross-platform solution. I recommend the helper library readchar
which can be installed with pip install readchar
. It works on Linux, macOS, and Windows and on either Python 2 or Python 3.
import readchar
print("Press Any Key To Exit")
k = readchar.readchar()
How to continue OR exit the program by pressing keys
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:
How to make my program stop running when I press a certain key
use sys.exit(). At the top of your code like here
import sys
than in the finale part of your code implement the exit part
restart = input("Do want to continue? Press \"y\" to continue or press any key to
end ")
if restart == "y" or restart == "Y":
print("")
main()
else:
print("shutting down")
sys.exit()
Get python program to end by pressing anykey and not enter
Usually, one would use input('>> ')
(or raw_input('>> ')
with Python3) in order to obtain a user command. However, this does require the user to submit the data after it is entered. So for your example, the user would type c then hit the Enter key.
If you're using Windows, then I think what you're after may be close to this answer. This example imports a library, msvcrt, which you can use to detect keyboard hits (using msvcrt.kbhit()
). So the user would type c and your code could respond to that keystroke, without having to wait for the Enter key. Of course you will have to process the keys (i.e. check that the button was indeed a c) before executing the desired code (i.e. quit the application).
Edit: This answer assumes you have a while()
loop doing stuff and/or waiting for user input. Such as the following:
import msvcrt
print("Hi everyone! This is just a quick sample code I made")
print("Press anykey to end the program.")
while(True):
# Do stuff here.
if msvcrt.kbhit():
# The user entered a key. Check to see if it was a "c".
if (msvcrt.getch() == "c"):
break
elif (msvcrt.getch() == <some other character>):
# Do some other thing.
Of course to end the program for any keyboard hit, just get rid of the part that checks to see if the key is a "c".
How to do hit any key in python?
try:
# Win32
from msvcrt import getch
except ImportError:
# UNIX
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
return sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
How do I wait for a pressed key?
In Python 3, use input()
:
input("Press Enter to continue...")
In Python 2, use raw_input()
:
raw_input("Press Enter to continue...")
This only waits for the user to press enter though.
On Windows/DOS, one might want to use msvcrt
. The msvcrt
module gives you access to a number of functions in the Microsoft Visual C/C++ Runtime Library (MSVCRT):
import msvcrt as m
def wait():
m.getch()
This should wait for a key press.
Notes:
In Python 3, raw_input()
does not exist.
In Python 2, input(prompt)
is equivalent to eval(raw_input(prompt))
.
How to stop a program when a key is pressed in python?
from pynput import keyboard
import time
break_program = False
def on_press(key):
global break_program
print (key)
if key == keyboard.Key.end:
print ('end pressed')
break_program = True
return False
with keyboard.Listener(on_press=on_press) as listener:
while break_program == False:
print ('program running')
time.sleep(5)
listener.join()
Related Topics
Using a Global Variable With a Thread
How to Read Pdf Files One by One from a Folder in Python
Setting Matplotlib Colorbar Range
How to Serialize Sqlalchemy Result to Json
How to Get the Coordinates of the Bounding Box in Yolo Object Detection
Convert the String 2.90K to 2900 or 5.2M to 5200000 in Pandas Dataframe
Animate a Rotating 3D Graph in Matplotlib
Use Tqdm Progress Bar With Pandas
Splitting Dataframe into Multiple Dataframes
How to Add Pandas Data to an Existing CSV File
Typeerror: Unsupported Operand Type(S) for ** or Pow(): 'List' and 'Int'
Python - Split a List of Dicts into Individual Dicts
Render_Template in Python-Flask Is Not Working
How to Force Pip to Reinstall the Current Version
How to Obtain Second and Fourth Word from Each Line in a File
How to Share Single Sqlite Connection in Multi-Threaded Python Application