Python, Press Any Key To Exit

A little late to the game, but I wrote a library a couple years ago to do exactly this. It exposes both a pause() function with a customizable message and the more general, cross-platform getch() function inspired by this answer.

Install with pip install py-getch, and use it like this:

from getch import pause
pause()

This prints 'Press any key to continue . . .' by default. Provide a custom message with:

pause('Press Any Key To Exit.')

For convenience, it also comes with a variant that calls sys.exit(status) in a single step:

pause_exit(0, 'Press Any Key To Exit.')

Check it out.


I would discourage platform specific functions in python if you can avoid them, but you could use the built-in msvcrt module.

from msvcrt import getch

junk = getch() # Assign to a variable just to suppress output. Blocks until key press.

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

If you are on windows then the cmd pause command should work, although it reads 'press any key to continue'

import os
os.system('pause')

The linux alternative is read, a good description can be found here