A classic of early text-based interfaces... Any way to do it in Python? I tried getch(), but it doesn't really work (for instance, if you hit Enter to confirm a menu selection, and then it goes to a "press any key" thing with getch(), getch() will pick up the Enter keypress.)
The simpliest way is an easygui or Tkinter/PMW dialog box with one button. However, this is something found on the web long ago. It is probably also possible to do with ncurses.
import termios, sys, os
#import termios, TERMIOS, sys, os
TERMIOS = termios
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new = new & ~TERMIOS.ICANON & ~TERMIOS.ECHO
new[TERMIOS.VMIN] = 1
new[TERMIOS.VTIME] = 0
termios.tcsetattr(fd, TERMIOS.TCSANOW, new)
c = None
c = os.read(fd, 1)
termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)
if __name__ == '__main__':
print 'type something'
s = ''
c = getkey()
if c == 'q':
print 'got ("q" = end)', c
s = s + c
# press any key to continue function
def anykey(prompt="Press any key to continue...", failChars=""):
Displays a prompt to the user, then waits for the user to press a key.
Accepts a string for prompt, and a string containing all characters for which it should return False.
Returns False if the char pressed was in the failChars string, True otherwise.
Raises KeyboardInterrupt on Ctrl + C'''
from msvcrt import getch, kbhit
ch = getch()
if ch == '\x03':
return (ch not in failChars)
# end anykey definition
I made it return a bool so it is suitable for using in a loop. For example...
while anykey("Press 'q' to quit.", 'qQ'):
pass # keep prompting until user presses 'q' or 'Q'
It also deals with the problem of getch() not handling Ctrl+C properly. It's a little messy, but it works, and it's not extremely complicated.