[personal profile] archerships
Suppose you want to write a Python program that solicits input from a the user, but goes ahead anyway with a default value if they don't respond in say, 5 seconds. The following snippet of code implements such a thing:



#!/usr/bin/env python

import select 
import sys 


def tester():

    while True: 
        print """Continue? (type "Y" to continue, or "Q" to quit)""" 
        r, w, e = select.select( [sys.stdin], [], [], 5.0)
        if r == []:
            answer = "Y"
        else:
            answer = sys.stdin.readline().strip().upper()

        print "answer: %s" % answer

        if answer == "Q" or answer == "QUIT":
            print "Okay, fine.  Be that way."
            sys.exit(0)
        if answer == "N" or answer == "NO":
            print "Wah! Parting is such sweet sorrow."
            sys.exit(0)
        if answer != "Y" and answer != "YES":
            print "Watchoo talkin' bout, Willis?"
        else: 
            print "And so our journey continues. Yay!"            

tester()


(Use raw_input() if you don't need a timeout.)