Alex Rivera | Logout

How do I wait for a pressed key?

Asked 2009-06-11T20:09:19.323
829

How do I make my python script wait until the user presses any key?

Edit
Report

3 Answers

49

If you are ok with depending on system commands you can use:

from __future__ import print_function
import os
import platform

if platform.system() == "Windows":
    os.system("pause")
else:
    os.system("/bin/bash -c 'read -s -n 1 -p \"Press any key to continue...\"'")
    print()

It has been verified to work with Python 2 and 3 on Windows, Linux and Mac OS X.

answered 2013-06-05T06:36:48.553
17

I don't know of a platform independent way of doing it, but under Windows, if you use the msvcrt module, you can use its getch function:

import msvcrt
c = msvcrt.getch()
print 'you entered', c

mscvcrt also includes the non-blocking kbhit() function to see if a key was pressed without waiting (not sure if there's a corresponding curses function). Under UNIX, there is the curses package, but not sure if you can use it without using it for all of the screen output. This code works under UNIX:

import curses
stdscr = curses.initscr()
c = stdscr.getch()
print 'you entered', chr(c)
curses.endwin()

Note that curses.getch() returns the ordinal of the key pressed so to make it have the same output I had to cast it.

answered 2011-05-17T21:42:22.250
-1

If you want to see if they pressed a exact key (like say 'b') Do this:

while True:
    choice = raw_input("> ")

    if choice == 'b' :
        print "You win"
        input("yay")
        break
answered 2012-06-19T03:42:22.907

Your Answer