Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

raw_input and timeout [duplicate]

I want to do a raw_input('Enter something: .'). I want it to sleep for 3 seconds and if there's no input, then cancel the prompt and run the rest of the code. Then the code loops and implements the raw_input again. I also want it to break if the user inputs something like 'q'.

like image 741
ykmizu Avatar asked Aug 12 '10 19:08

ykmizu


1 Answers

There's an easy solution that doesn't use threads (at least not explicitly): use select to know when there's something to be read from stdin:

import sys from select import select  timeout = 10 print "Enter something:", rlist, _, _ = select([sys.stdin], [], [], timeout) if rlist:     s = sys.stdin.readline()     print s else:     print "No input. Moving on..." 

Edit[0]: apparently this won't work on Windows, since the underlying implementation of select() requires a socket, and sys.stdin isn't. Thanks for the heads-up, @Fookatchu.

like image 82
rbp Avatar answered Sep 23 '22 03:09

rbp