faqts : Computers : Programming : Languages : Python : Common Problems

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 6 people (67%) answered Yes
Recently 1 of 3 people (33%) answered Yes

Entry

Is it possible to implement timeout on read?

Aug 21st, 2000 17:58
unknown unknown, Peter Schneider-Kamp, Gerrit Holl


Problem:

Is it possible to implement timeout on read?

eg.

answer = sys.stdin.readline()

but I want it to timeout after 30 seconds.


Solution:

Have a look at the select module. For an example how this can be used 
for a timeout (but for socket.read()) see:

http://www.timo-tasi.org/python/timeoutsocket.py

---------

It's not crossplatform, but on Unix, the signal module is your friend.

You could use such code:

<example>
#!/usr/bin/python

import signal
import sys

TIMEOUT = 10

def f(signum, frame):
    print "Too late!"
    print "Signal handler called with signal number", signum
    print frame, "is a", type(frame), "with some useful information"

signal.signal(signal.SIGALRM, f)
signal.alarm(TIMEOUT)

line = sys.stdin.readline()

print "I read: '%s'" % line
</example>

I don't know any cross-platform solution.

Please consult for details:
http://www.python.org/doc/current/lib/module-signal.html