Update Sep 2011: If you’re using Google’s Go Lang see Non blocking console read in Go. Thanks Ostsol
Heavily updated 9th January 2008: This post was originally entitled Non blocking console IO is not possible. Two helpful comments helped me see the error of my ways. Many thanks to ‘schlenk’ and ‘Bob’ for the help. Non blocking console IO is possible, it just isn’t (easily) portable. Read on to find out how.
I have been doing some programming exercises in Python, Java and ActionScript (Flex), using this list from Prashant N Mhatre. The first exercise sounds simple on the surface:
Display series of numbers (1,2,3,4, 5….etc) in an infinite loop. The program should quit if someone hits a specific key (Say ESCAPE key)
Displaying a list of numbers in an infinite loop is trivial, and stopping on Ctrl-C is trivial, but stopping on a key of your choice (let’s use ESC), makes the problem much more interesting.
By default the console on Linux and Windows is buffered. It does not send you character data until the Enter key is pressed. In Python the raw_input method will block until it gets input. In Java you can test the characters available, non blocking, using System.in.available(), but this still doesn’t fill up until Enter is pressed. There are two ways to solve this: