0

NOTES: Running Python 2.7, working on a macbook (OSX)

I want to query my user for an input, but if no input occurs after a time interval, run something else and try again. Here's what I have written:

import sys, select

def test():
    waittime = 4
    i, o, e = select.select( [sys.stdin], [], [], waittime)
    if i:
        print 'got i'
    else:
        print 'did not get i'
    test()

What this DOES: If user does not press [return], waits 3 seconds, prints 'did not get i', reruns the function. If user presses [return], if (i) statement runs indefinitely.

What I WANT it do do: If the user presses [return], print 'got i', rerun the function, WAIT FOR USER TO PRESS RETURN. If user does not press return, wait three seconds, print 'did not get i', try again.

Thanks in advance for any help! -Erik

  • 2
    Possible duplicate of [How to set time limit on input](http://stackoverflow.com/questions/2933399/how-to-set-time-limit-on-input) – Ahsanul Haque Dec 03 '16 at 07:14

1 Answers1

0

First I solved that with multithreading, but I guess it was overboard.

import sys,time,select

anidle = 0.0

while True:
    time.sleep(0.01)

    incoming = select.select([sys.stdin],[],[],0.0)[0]
    if len(incoming) > 0:
        anidle = 0.0
        aline = sys.stdin.readline()

        # process the input here
        print 'Input:', aline
        break

    anidle += 0.01
    if anidle > 4:

        # process no input for 4 seconds here
        print 'No input.'
        break
Organis
  • 6,618
  • 2
  • 9
  • 10
  • This WORKS! Thank you so much. I adapted it for my own personal use like so (working on a little game) by changing the (while True) to a (while health > 0) and where the hashtags for "process the input" I wrote health -= 20. – Erik Sandberg Dec 03 '16 at 17:15