Trapping Alarm Out Of Blocking READ
Quote:
>In LINUX, I'm trying to trap out of a blocking read to a tty device
>after a finite number of seconds. In abbreviated form, my code reads:
signals don't raise an exception; you have to set up a handler
function with signal.signal(signal.SIGALARM, myhandler). This
function gets called when the signal is received by the Python
process. (See the LibRef for the signal module:
http://www.python.org/doc/lib/node67.html)
However, a better approach may be the select module, which
provides an interface to the Unix select() function. select.select()
is passed 3 lists containing file objects, and returns 3 different
lists containing those objects that are ready for reading or writing.
select.select() has an optional timeout parameter, and will return
either when an object becomes ready for I/O or when time runs out.
For example, this opens /dev/tty, and prints "Type something!" every 5
seconds until you type something.
import os, select
# I'm not sure it's a good idea to use C stdio on things like /dev/tty
# or /dev/ttyS0. Anyone know?
term_fd=open('/dev/tty', 'r')
while (1):
# The 3 lists are for: reading, writing, exceptional conditions.
# We only care about reading in this case, so the last 2 lists
# are of no interest to us.
read_list, dummy, dummy = select.select([term_fd], [], [], 5)
if len(read_list)==0:
print 'Type something!'
else:
c=term_fd.read(1)
print 'You typed character', c
# End of script
select.select() is commonly used when you want a process to listen to
two or more sources of input such as pipes or sockets, and data can
become available from either socket at any time. MUDs and X servers
spend a lot of time in select() loops: wait for input from one of
several sources, handle the input, go back to waiting...
Andrew Kuchling
http://starship.skyport.net/crew/amk/