How to do "hit any key" in python?

Question:

How would I do a “hit any key” (or grab a menu option) in Python?

  • raw_input requires you hit return.
  • Windows msvcrt has getch() and getche().

Is there a portable way to do this using the standard libs?

Asked By: Nick

||

Answers:

From the python docs:

import termios, fcntl, sys, os
fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

try:
    while 1:
        try:
            c = sys.stdin.read(1)
            print "Got character", `c`
        except IOError: pass
finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

This only works for Unix variants though. I don’t think there is a cross-platform way.

Answered By: Isaiah
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)
Answered By: John Millikin
try:
  os.system('pause')  #windows, doesn't require enter
except whatever_it_is:
  os.system('read -p "Press any key to continue"') #linux
Answered By: Dustin Getz

on linux platform, I use os.system to call /sbin/getkey command, e.g.

continue_ = os.system('/sbin/getkey -m "Please any key within %d seconds to continue..." -c  10')
if continue_:
   ...
else:
   ...

The benefit is it will show an countdown seconds to user, very interesting 🙂

Answered By: Congbin Guo

A couple years ago I wrote a small library to do this in a cross-platform way (inspired directly by John Millikin’s answer above). In addition to getch, it comes with a pause function that prints 'Press any key to continue . . .':

pause()

You can provide a custom message too:

pause('Hit any key')

If the next step is to exit, it also comes with a convenience function that calls sys.exit(status):

pause_exit(status=0, message='Hit any key')

Install with pip install py-getch, or check it out here.

Answered By: Joe

I implemented it like the following in Windows.
getch() takes a one single character

import msvcrt
char = 0
print 'Press any key to continue'
while not char:
    char = msvcrt.getch()
Answered By: v_kumar

Another option:

import keyboard
print("Press any key to continue")
keyboard.read_key()
print("to be continued...")
Answered By: Bill Mol
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.