#!/usr/bin/env python import select import sys import tty FD_IN = sys.stdin.fileno() def wait_for_input(prompt, timeout): """Print a prompt, then wait for input, with a timeout. The timeout is specified as a number of seconds, in floating point. If any input is provided, then it will return True. If the timeout occurs, then False will be returned. Pass None for the timeout, if a timeout is not required. """ sys.stdout.write(prompt) sys.stdout.flush() # want to save/restore the terminal attributes attrs = tty.tcgetattr(FD_IN) try: # put the tty into cbreak mode, rather than waiting for EOL. # use TCSANOW to avoid flushing the input. tty.setcbreak(FD_IN, tty.TCSANOW) # wait for input for seconds inputs, _unused, _unused = select.select([FD_IN], [], [], timeout) finally: # restore the attributes tty.tcsetattr(FD_IN, tty.TCSANOW, attrs) # something arrived on STDIN if inputs: # drain all input that was provided tty.tcflush(FD_IN, tty.TCIFLUSH) return True # no input return False if __name__ == '__main__': print wait_for_input('Press any key: ', 3)